-
Notifications
You must be signed in to change notification settings - Fork 342
/
Peak Element.cpp
52 lines (37 loc) · 983 Bytes
/
Peak Element.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
49
50
51
52
#include<bits/stdc++.h>
using namespace std;
/********************************************************
Problem Statement:
Given an array of n elements, find the
position of the element which is greater than
or equal to both of its neighboring elements.
Basic Idea:
The naive approach is to use a simple linear scan.
But we can do even better than that by using
modified version of Binary Search which would run
in time complexity of O(logn).
Note:
This program uses 0-based indexing.
********************************************************/
int findPeakElement(vector<int>& arr, int n) {
int l = 0, r = n - 1;
while(l < r){
int mid = (r-l)/2 + l;
if(arr[mid] > arr[mid+1]){
r = mid;
}
else {
l = mid + 1;
}
}
return l;
}
int main(){
int n;
cin >> n;
vector <int> arr(n);
for(int& i : arr){
cin >> i;
}
cout << "The peak is at position: " <<findPeakElement(arr, n);
}