Solution: Peak Element
This review discusses the solution of the Peak Element Challenge in detail.
We'll cover the following...
Solution #1
One simple way to solve this problem is:
Press + to interact
class PeakElement {public static int findPeak(int[] array) {//calculating array lengthint len = array.length;if (len == 0) {return -1;}if (len == 1) {return array[0];}if (array[0] >= array[1]) {return array[0];}//traversing arrayfor (int i = 1; i < len - 1; i++) {//if current value is greater than previous and the next value return itif ((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:
- Start from the beginning and compare each element with its neighbors.
- 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 possible ...