Prerequisites:- None
Problem :- Given an array A of size N, find and print all the peak elements in the array. A peak element is one which is strictly greater than any of its adjacent elements.
If there is no peak element in an array, print -1.
Explanation :-
Iterate over each element of the array and print it if the element is greater than its left and right adjacent elements. If you don’t find any such element, print -1.
Solution :-
C++ Solution : -
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> A(n);
// Input array elements
for(int i = 0; i < n; i++) {
cin >> A[i];
}
bool hasPeak = false;
for(int i = 0; i < n; i++) {
if((i == 0 || A[i] > A[i-1]) && (i == n-1 || A[i] > A[i+1])) {
cout << A[i] << " ";
hasPeak = true;
}
}
if(!hasPeak) {
cout << "-1";
}
return 0;
}