Skip to content

Commit

Permalink
Create 0852_Peak_Index_in_a_Mountain_Array.java
Browse files Browse the repository at this point in the history
  • Loading branch information
mkhuzaima authored Oct 12, 2023
1 parent 3f36c76 commit 475eec5
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions 0852_Peak_Index_in_a_Mountain_Array.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// id: 852
// Name: Peak Index in a Mountain Array
// link: https://leetcode.com/problems/peak-index-in-a-mountain-array/
// Difficulty: Medium

class Solution {
public int peakIndexInMountainArray(int[] arr) {
int peakIndex = 0;
int left = 0;
int right = arr.length - 1;

while (left < right) {
int mid = ( left + right ) / 2;

// check if at left peak
if (arr[mid] > arr[mid-1] && arr[mid] > arr[mid+1]) {
peakIndex = mid;
break;
} else if (arr[mid] > arr[mid-1]) {
// peak is at right
left = mid ;
} else if (arr[mid] > arr[mid+1]) {
right = mid ;
}
}


return peakIndex;
}
}

0 comments on commit 475eec5

Please sign in to comment.