-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMountain.java
38 lines (35 loc) · 1.54 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
32
33
34
35
36
37
38
// Leetcode - https://leetcode.com/problems/peak-index-in-a-mountain-array/description/
public class Mountain
{
public static void main(String[] args) {
int arr[] = {0,5,10,2};
int ans = peakIndexInMountainArray(arr);
System.out.println(ans);
}
public static int peakIndexInMountainArray(int[] arr)
{
int start = 0;
int end = arr.length - 1;
while(start < end)
{
int mid = start + (end - start) / 2;
if(arr[mid] > arr[mid + 1])
{
// you are in the descending part of the array
// this may be the ans but look at left side too
// this is why end != mid - 1
end = mid;
}
else{
// you are in the ascending part of the 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 our 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 because of above line that is the best possible answer
return start; // or return end as both are =
}
}