Skip to content

Commit ddb9efa

Browse files
authored
added java file
1 parent 0ed87b0 commit ddb9efa

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

PeakIndex.java

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

0 commit comments

Comments
 (0)