Skip to content

Commit 637b7e4

Browse files
authored
_Find_Peak_element.java
1 parent ea13071 commit 637b7e4

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

0162_Find_Peak_element.java

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
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+
}

0 commit comments

Comments
 (0)