Find Peak Element

By   Tewodros   Date Posted: Nov. 24, 2021  Hits: 761   Category:  Algorithm   Total Comment: 0             A+ A-


side

Given a list of numbers as an array we would like to find the index of the peak element which is greater than the numbers before and after it. 

Example 

Let A= {1, 2, 1, 3, 5, 5, 4}  Ans: 1 since the number at index 1 which is 2 is greater than the the numbers before and after it.

Let A= {1, 0, 1, 3, 5, 6, 4}  Ans: 5 since the number at index 5 which is 6 is greater than the the numbers before and after it.

Solution:

We can iterate through the array using a for loop and see if the number is greater than the numbers before and after it. A pick can also exist in the end of the array and in that case we can simply check using the A.Max() math function to do that. 

              for (int i = 0; i < A.Length - 2; i++)   {

                   if (A[i] < A[i + 1] && A[i + 1] > A[i + 2])

                       return i+1;

               }

 

               if (A.Max() == A[A.Length - 1])   {

                   return A.Length - 1;

               }

 

               return 0;


Tags



Back to Top



Related Blogs






Please fill all fields that are required and click Add Comment button.

Name:*
Email:*
Comment:*
(Only 2000 char allowed)


Security Code:* fwukcw

Back to Top