Search⌘ K
AI Features

Solution: Peak Element

Explore two approaches to find a peak element in an array: a simple linear scan and a more efficient divide and conquer method. Understand how to apply recursive logic to narrow down the search, achieving logarithmic time complexity for faster performance in algorithm design.

Solution #1

One simple way to solve this problem is:

Java
class PeakElement {
public static int findPeak(int[] array) {
//calculating array length
int len = array.length;
if (len == 0) {
return -1;
}
if (len == 1) {
return array[0];
}
if (array[0] >= array[1]) {
return array[0];
}
//traversing array
for (int i = 1; i < len - 1; i++) {
//if current value is greater than previous and the next value return it
if ((array[i] >= array[i - 1]) & (array[i] >= array[i + 1])) {
return array[i];
}
}
if (array[len - 1] >= array[len - 2]) {
return array[len - 1];
}
return -1;
}
/* Driver program to test above functions */
public static void main(String args[]) {
int[] array = { 7, 11, 22, 13, 4, 0 };
System.out.println("Peak element is: " + findPeak(array));
int[] array1 = {0,3,100,2,-1,0};
System.out.println("Peak element is: " + findPeak(array1));
}
}

In the code above, we:

  1. Start from the beginning and compare each element with its neighbors.
  2. Return the peak element wherever it is found in the array.

There must always be one peak element in an array with distinct elements but it’s ...