Skip to content

Commit 70c3155

Browse files
authored
Add files via upload
1 parent 55baa10 commit 70c3155

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

PeakIndexMountainArray.java

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
//https://leetcode.com/problems/peak-index-in-a-mountain-array/
2+
public class PeakIndexMountainArray {
3+
4+
//We can traverse till end of array where we can find increasing order suddenly decreasing
5+
//O(n)
6+
public static int peakIndexInMountainArrayCompleteTraversal(int[] arr) {
7+
int max=-1,index=0;
8+
for(int i=0;i<arr.length;i++) {
9+
if(arr[i]>max) {
10+
max=arr[i];
11+
index=i;
12+
} else {
13+
return index;
14+
}
15+
}
16+
return index;
17+
}
18+
19+
//Solving using binary Seach
20+
//O(logn)
21+
public static int peakIndexInMountainArrayBinarySearch(int[] arr) {
22+
return mids(0,arr.length-1,arr);
23+
}
24+
25+
public static int mids(int left, int right,int[] arr) {
26+
if(left==right) {
27+
return left;
28+
}
29+
if(left>=0 && right<arr.length) {
30+
int mid=(left+right)/2;
31+
if(mid+1<arr.length && arr[mid]>arr[mid+1]) {
32+
if(mid-1>=0 && arr[mid]>arr[mid-1]) {
33+
return mid;
34+
}
35+
else {
36+
return mids(left,mid,arr);
37+
}
38+
} else {
39+
return mids(mid,right,arr);
40+
}
41+
}
42+
return 0;
43+
}
44+
45+
46+
public static void main(String args[]) {
47+
System.out.println("Expected index 1:");
48+
System.out.println(peakIndexInMountainArrayCompleteTraversal(new int[]{0,10,5,2}));
49+
System.out.println(peakIndexInMountainArrayBinarySearch(new int[]{0,10,5,2}));
50+
}
51+
}

0 commit comments

Comments
 (0)