...

/

Solution: Peak Element

Solution: Peak Element

This review discusses the solution of the Peak Element Challenge in detail.

Solution #1: Brute Force

One simple way to solve this problem is to start from the beginning, compare each element with its neighbors, and just return the peak element wherever you find it in the array.

Press + to interact
#include<iostream>
using namespace std;
/* Function to find the peak element in the array */
int findPeak(int arr[], int n){
if(n==1) // Handling the edge case (if the array is of size 1)
return -1;
for(int i = 1; i<n-1; i++){
if(arr[i] >= arr[i-1] && arr[i] >= arr[i+1])
return i;
}
if(arr[0] >= arr[1])
return 0;
if(arr[n-1] >= arr[n-2])
return n-1;
}
/* Driver program to check above functions */
int main() {
int arr[] = {7,11,22,13,4,0};
int x = sizeof(arr);
int y = sizeof(arr[0]);
int arrSize = x / y;
cout << "One peak point index is: " << findPeak(arr, arrSize) << endl;
}

There must always be one peak element in an array with distinct elements, but it’s possible that the array is ...

Access this course and 1400+ top-rated courses and projects.