Skip to content
thesarfo

Reference

Find the Peaks (1D Array)

Finding every index whose value is strictly greater than both its neighbors.

views 0

An element strictly greater than both neighbors; the first and last elements can never be peaks. [1,4,3,8,5] → peaks at indices [1,3]. (LeetCode 2951)

class Solution {
public List<Integer> findPeaks(int[] mountain) {
int n = mountain.length;
List<Integer> result = new ArrayList<>();
for(int i = 0; i < n; i++){
if(i == 0 || i == n-1){
continue;
}
if(mountain[i] > mountain[i-1] && mountain[i] > mountain[i+1]){
result.add(i);
}
}
return result;
}
}