Search⌘ K
AI Features

Solution: Peak Element

Explore methods to identify a peak element in an array by comparing neighbors. Understand the brute force approach and improve your solution using divide and conquer to achieve logarithmic time complexity, boosting efficiency in algorithmic problem-solving.

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.

C++
#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 sorted in ascending order like ...