Peak element In CPP
Peak element
Given an
array A of integers. The task is to find a peak element in it.
An array
element is peak if it is not smaller than its neighbors. For corner elements,
we need to consider only one neighbor.
Note: There may be multiple peak element possible, in
that case you may return any valid index.
Input Format:
The first
line of input contains an integer T denoting the number of test cases. Then T
test cases follow. Each test case contains an integer N. Then in the next line
are N space separated values of the array.
Output Format:
For each
test case output will be 1 if the index returned by the function is an peak
index.
User Task:
You don't
have to take any input. Just complete the provided function peakElement() and
return the valid index.
Constraints:
1 <= T
<= 100
1 <= N
<= 100
1 <= A[]
<= 1000
Example:
Input:
2
3
1 2 3
2
3 4
Output:
1
1
Explanation:
Testcase 1: In the given array, 3 is the peak element.
Testcase 2: 4 is the peak element.
#include<bits/stdc++.h>
using
namespace std;
//Position
this line where user code will be pasted.
int main() {
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++)
{
cin>>a[i];
}
bool f=0;
int A =
peakElement(a,n);
if(n==1)
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;
}
int
peakElement(int arr[], int n)
{
for(int i=0;i<n;i++)
{
if(i==0 && arr[i]>=arr[i+1])
return i;
else if(i==n-1 &&
arr[i]>=arr[i-1])
return i;
else if(arr[i]>=arr[i-1] &&
arr[i]>=arr[i+1])
return i;
}
return -1;
}