-
Notifications
You must be signed in to change notification settings - Fork 7
/
Mountain.java
31 lines (29 loc) · 1.38 KB
/
Mountain.java
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
public class Mountain {
public static void main(String[] args) {
}
public int peakIndexInMountainArray(int[] arr){
int start = 0;
int end = arr.length-1;
while (start< end){
// find the middle element
// int mid = (start + mid)/2;
//might be possible that(start+end)
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 elemen
}
}
// 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 cause of above line that is the best possible ans
return start; // or return end as both are =
}
}