-
Notifications
You must be signed in to change notification settings - Fork 619
/
peak_value_linear_search.cpp
46 lines (41 loc) · 962 Bytes
/
peak_value_linear_search.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
/**An array element is a peak if it is NOT smaller than
its neighbours. For corner elements, we need to
consider only one neighbour.
Since an array always have a maximum value therefore an peak element always be there and there can be many peak element.
Approach : We will iterate for entire loop and check if peak element is found.
**/
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cout << "Enter the number of elements in the array : ";
cin >> n;
vector<int> v(n);
cout << "\nEnter the elements of the array : \n";
for (int i = 0; i < n; i++)
{
cin >> v[i];
}
int peak;
for(int i=0;i<n;i++)
{
if( (i==0 && v[0]>=v[1]) || (i==n-1 && v[n-1]>=v[n-2]) || (v[i]>=v[i-1] && v[i]>=v[i+1]) )
{
peak = v[i];
break;
}
}
cout << "Peak element : " << peak << "\n";
return 0;
}
/**
Eg. :
Input:
7
10 20 15 2 23 90 67
Output:
Peak element : 20
Time Complexity : O(N)
Space Complexity : O(N)
**/