Tuesday, July 25th
Finding the peak in a mountain array is today's problem
An array is designed like a mountain, where values increase from beginning to a peak, when values decline to the end of the array. We are tasked with finding the peak of the mountain. The solution must be logarithmic time, because finding the max in an array is a trivial linear time one-liner
Locating a value in logarithmic time beckons binary search
Instead of using binary search to look for a target value, we are looking for a peak. The peak, which is guaranteed to exist, occurs when a value has both a right and left neighbor with a smaller value. So we modify binary search to test for the peak condition
Initialize variables to represent the indices of the middle value, left of middle, and right of middle
With the middle, middle right, and middle left indices, we test for a peak. We find the array values at m, ml, and mr, and test if the middle value is greater than the values to the immediate left and right. If the conditions are met, were return m, the index of the peak;
if( arr[m]>arr[ml] && arr[m]>arr[mr] ) return m;
The full algorithm is below:
The algorithm returns -1 at the end because it was required by the compiler, but since a peak is guaranteed to exist, and the array is of at least length 3 so we don't need to test boundary conditions, the return -1 should never occur, which held up for all test cases
The problem is listed as a medium, but can be solved with binary search by basically modifying one line

Comments
Post a Comment