-
Notifications
You must be signed in to change notification settings - Fork 0
/
Problem no 162.java
38 lines (33 loc) · 1.54 KB
/
Problem no 162.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
// Ques : Find Peak Element
// Ques Link : https://leetcode.com/problems/find-peak-element/
// Just copied the entire solution of problem no. 852
package com.nitin;
public class MountainArray {
public static void main(String[] args) {
int[] arr = {0, 1, 3, 7, 8, 9, 6, 4, 3, 2, 0};
int ans = peakIndexInMountainArray(arr);
System.out.println(ans);
}
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 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 =
}
}