-
Notifications
You must be signed in to change notification settings - Fork 0
/
Peak_Element.cpp
83 lines (74 loc) · 1.52 KB
/
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
//{ Driver Code Starts
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
/* The function should return the index of any
peak element present in the array */
// arr: input array
// n: size of array
class Solution
{
public:
int peakElement(int nums[], int n)
{
if(n == 1) return 0;
if(nums[0] > nums[1]) return 0;
if(nums[n - 1] > nums[n - 2]) return n - 1;
int low = 1;
int high = n - 2;
while(low <= high)
{
int mid = (low + high) / 2;
if(nums[mid] >= nums[mid - 1] && nums[mid] >= nums[mid + 1])
{
return mid;
}
else if(nums[mid] > nums[mid - 1])
{
low = mid + 1;
}
else
{
high = mid - 1;
}
}
return -1;
}
};
//{ Driver Code Starts.
int main() {
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
int a[n], tmp[n];
for(int i=0;i<n;i++)
{
cin>>a[i];
tmp[i] = a[i];
}
bool f=0;
Solution ob;
int A = ob. peakElement(tmp,n);
if(A<0 and A>=n)
cout<<0<<endl;
else
{
if(n==1 and A==0)
f=1;
else if(A==0 and a[0]>=a[1])
f=1;
else if(A==n-1 and a[n-1]>=a[n-2])
f=1;
else if(a[A]>=a[A+1] and a[A]>= a[A-1])
f=1;
else
f=0;
cout<<f<<endl;
}
}
return 0;
}
// } Driver Code Ends