'Find peaks in array (with neighborhood)

Suppose I have a 1D array, and I want to find peaks. The difference from classic peak finding is that I need to check not only its neighbors, but I need to check n left neighbors and n right neighbors. For example my array is following:

[1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1]

And n = 4. I need to check every subarray with length 4 + 1 + 4 and see if the middle element is the maximum.

In the case:

[5,6,7,8,9,8,7,6,5], 9 is the peak.

But this does not sound very efficient. So what can be a better solution? When I find a peak, I can ignore the next n elements I think.



Solution 1:[1]

Try to avoid unimportant comparison. Example

public class NewClass12 {
   static int [] arr = {1,2,3,4,5,3,2,1,0,9,7,6,5,4,3,2,1};
      public static void main(String [] args){
        int n = 4; //bounds
        boolean peakFound = false;
        int peak = 0;
        //iterate of data
        for(int k = n; k<=arr.length-n+1;k++){
           //check data within bounds
           for (int i = 1;i <=n;i++){
              if(arr[k]<arr[k-i] || arr[k]<arr[k+i]){
                peakFound = false;
                break;
            }
            else{
               peakFound = true; 
               peak = arr[k];
            }
        } 
        if(peakFound)
            System.out.println(peak);
     }
   }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Martin Frank