File tree Expand file tree Collapse file tree 1 file changed +25
-0
lines changed Expand file tree Collapse file tree 1 file changed +25
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public int findPeakElement (int []arr ) {
3
+ int start = 0 ;
4
+ int end = arr .length - 1 ;
5
+
6
+ while (start < end ) {
7
+ int mid = start + (end - start ) / 2 ;
8
+ if (arr [mid ] > arr [mid +1 ]) {
9
+ // you are in dec part of array
10
+ // this may be the ans, but look at left
11
+ // this is why end != mid - 1
12
+ end = mid ;
13
+ } else {
14
+ // you are in asc part of array
15
+ start = mid + 1 ; // because we know that mid+1 element > mid element
16
+ }
17
+ }
18
+ // in the end, start == end and pointing to the largest number because of the 2 checks above
19
+ // start and end are always trying to find max element in the above 2 checks
20
+ // hence, when they are pointing to just one element, that is the max one because that is what the checks say
21
+ // more elaboration: at every point of time for start and end, they have the best possible answer till that time
22
+ // and if we are saying that only one item is remaining, hence cuz of above line that is the best possible ans
23
+ return start ; // or return end as both are =
24
+ }
25
+ }
You can’t perform that action at this time.
0 commit comments