-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBS_Peak_Mountain_Array.java
More file actions
38 lines (34 loc) · 1.61 KB
/
Copy pathBS_Peak_Mountain_Array.java
File metadata and controls
38 lines (34 loc) · 1.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package dsa;
// https://leetcode.com/problems/peak-index-in-a-mountain-array/
// https://leetcode.com/problems/find-peak-element/
public class BS_Peak_Mountain_Array {
public static void main(String[] args) {
int[]arr={0,1,5,6,10,9,7,3,2};
//int ans=peakIndexInMountainArray(arr);
//System.out.println(ans);
}
public int peakIndexInMountainArray(int[]arr){
int start=0;
int end= arr.length-1;
while (start<end){
//int mid=start+end/2; // might be possible that (start + end) exceeds the range of int in java
int mid=start+(end-start)/2;
if (arr[mid]>arr[mid+1]) {
// you are in dec part of array
// this may be the ans, but look at left
// this is why end != mid - 1
end=mid;
}
else {
// you are in asc part of array
start=mid+1;// because we know that mid+1 element > mid element
}
}
// in the end, start == end and pointing to the largest number because of the 2 checks above
// start and end are always trying to find max element in the above 2 checks
// hence, when they are pointing to just one element, that is the max one because that is what the checks say
// more elaboration: at every point of time for start and end, they have the best possible answer till that time
// and if we are saying that only one item is remaining, hence cuz of above line that is the best possible ans
return start; // or return end as both are =
}
}