The Peak of Mountain Array
A mountain array is defined as an array that
 has at least 3 elements
 let's call the element with the largest value the "peak", with index
k
. The array elements monotonically increase from the first element toA[k]
, and then monotonically decreases fromA[k + 1]
to the last element of the array. Thus creating a "mountain" of numbers.
Find the index of the peak element. Assume there is no duplicate.
Input: 0 1 2 3 2 1 0
Output: 3
Explanation: the largest element is 3 and its index is 3.
Try it yourself
Explanation
The peak element is always larger than the next element. Applying the filter of arr[i] > arr[i + 1]
we get a boolean array. A minor edge case is for the last element as it has no next element. In that case, we assume its next element is negative infinity.
Now the problem is reduced to finding the first true
element in a boolean array. And we already know how to do this from Find Boundary module.
1  1 
 
2  2  
3  3 
 
4   
 
4  + 
 
5  + 
 
6  + 
 
7  + 
 
8  + 
 
9  + 
 
10  + 
 
11  + 
 
12  + 
 
13  +  
14  + 
 
15  +  
5  16 
 
6  17 
 
7  18 
 
8  19 

Loading full content...