-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path852. Peak Index in a Mountain Array.cpp
48 lines (48 loc) · 1.25 KB
/
852. Peak Index in a Mountain Array.cpp
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
39
40
41
42
43
44
45
46
47
48
#include <iostream>
#include <vector>
using namespace std;
int peakIndexInMountainArray(vector<int>& arr) {
int start = 0;
int end = arr.size()-1;
int ans = 0;
while(start<=end){
int mid = start+(end-start)/2;
if(mid!=0){
//return peak element
if(arr[mid]>arr[mid-1] && arr[mid]>arr[mid+1]){
ans = mid;
break;
}
// Upward slope
if(arr[mid]>arr[mid-1] && arr[mid]<arr[mid+1]){
start = mid+1;
}
// Downward slope
if(arr[mid]<arr[mid-1] && arr[mid]>arr[mid+1]){
end = mid-1;
}
}
if(mid==0){
if(arr[mid]<arr[mid+1]){
return mid+1;
}
else{
return mid;
}
}
}
return ans;
}
int main() {
// Write C++ code here
int n;
cin>>n;
vector<int> v;
for(int i=0;i<n;i++){
int x;
cin>>x;
v.push_back(x);
}
cout << peakIndexInMountainArray(v);
return 0;
}