File tree Expand file tree Collapse file tree 1 file changed +27
-0
lines changed Expand file tree Collapse file tree 1 file changed +27
-0
lines changed Original file line number Diff line number Diff line change 1+ //https://leetcode.com/problems/peak-index-in-a-mountain-array/
2+
3+ class Solution {
4+ public int peakIndexInMountainArray (int [] arr ) {
5+ int start = 0 ;
6+ int end = arr .length - 1 ;
7+
8+ while (start < end ) {
9+ int mid = start + (end - start ) / 2 ;
10+ if (arr [mid ] > arr [mid +1 ]) {
11+ // you are in dec part of the array
12+ // this may be the ans, but look at left
13+ end = mid ;
14+ } else {
15+ // arr[mid + 1] > arr[mid]
16+ // you are in inc part of the array
17+ start = mid + 1 ;
18+ }
19+ }
20+
21+ // In the end, start == end and pointing to the largest number because of the 2 checks
22+ // start and end are always trying to find max element in the above 2 checks
23+ // hence, when they are pointing to just one element, that is the max element
24+ // At every point of time of start and end, there may be a best possible ans at that particular time
25+ return end ;
26+ }
27+ }
You can’t perform that action at this time.
0 commit comments