Find subarray of Length K with Maximum Peak

Given an array arr[] of length n and a positive integer K, we have to find a subarray of length K which has maximum peak inside in it.

Peaks of the segment [l, r] are those indexes such that l < i < r, a[i-1] < a[i] and a[i+1] < a[i].

Note: The boundary indexes l and r for the segment are not peaks. If there are many subarrays with maximum peak, then print that subarray whose has minimum left index.

Examples:

Input :
arr = {3, 1, 4, 1, 5, 9, 2, 6}, k = 7
Output:
Left = 1
Right = 7
Peak = 2
Explanation:
There are two subarray with length 7 i.e [1, 7] and [2, 8]. Both subarray has 2 peak inside it i.e 3 and 6 index are the peak in both the subarray. We have to return the subarray with minimum l and maximum peak i.e l = 1 and peak = 2.



Input:
arr = {3, 2, 3, 2, 1}, k = 3
Output :
Left = 2
Right = 4
Peak = 1
Explanation:
Only one subarray whose length is 3 and number of peak inside it is 1 i.e. l =2 and peak is i = 3.

Approach:

The approach to solve this problem is to use a sliding window, where we slide across window size of K, and find the total count of peaks in every window, whichever windows gives the maximum number of peaks will be the answer. While moving the right index, we check if an index added is a peak, we increase the count, and while moving the left index, we check if the removed index is a peak, if it is, then decrease the count. We have a window of size K always.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation to Find subarray
// of Length K with Maximum Peak
  
#include <bits/stdc++.h>
using namespace std;
  
// Function to find the subarray
void findSubArray(int* a, int n, int k)
{
    // Make prefix array to store
    // the prefix sum of peak count
    int pref[n];
  
    pref[0] = 0;
  
    for (int i = 1; i < n - 1; ++i) {
  
        // Count peak for previous index
        pref[i] = pref[i - 1];
  
        // Check if this element is a peak
        if (a[i] > a[i - 1] && a[i] > a[i + 1])
  
            // Increment the count
            pref[i]++;
    }
  
    int peak = 0, left = 0;
  
    for (int i = 0; i + k - 1 < n; ++i)
  
        // Check if number of peak in the sub array
        // whose l = i is greater or not
        if (pref[i + k - 2] - pref[i] > peak) {
            peak = pref[i + k - 2] - pref[i];
            left = i;
        }
  
    // Print the result
    cout << "Left = " << left + 1 << endl;
    cout << "Right = " << left + k << endl;
    cout << "Peak = " << peak << endl;
}
  
// Driver code
int main()
{
    int arr[] = { 3, 2, 3, 2, 1 };
  
    int n = sizeof(arr) / sizeof(arr[0]);
  
    int k = 3;
  
    findSubArray(arr, n, k);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation to Find subarray
// of Length K with Maximum Peak
  
class GFG{
   
// Function to find the subarray
static void findSubArray(int []a, int n, int k)
{
    // Make prefix array to store
    // the prefix sum of peak count
    int []pref = new int[n];
   
    pref[0] = 0;
   
    for (int i = 1; i < n - 1; ++i) {
   
        // Count peak for previous index
        pref[i] = pref[i - 1];
   
        // Check if this element is a peak
        if (a[i] > a[i - 1] && a[i] > a[i + 1])
   
            // Increment the count
            pref[i]++;
    }
   
    int peak = 0, left = 0;
   
    for (int i = 0; i + k - 1 < n; ++i)
   
        // Check if number of peak in the sub array
        // whose l = i is greater or not
        if (pref[i + k - 2] - pref[i] > peak) {
            peak = pref[i + k - 2] - pref[i];
            left = i;
        }
   
    // Print the result
    System.out.print("Left = " +  (left + 1) +"\n");
    System.out.print("Right = " +  (left + k) +"\n");
    System.out.print("Peak = " +  peak +"\n");
}
   
// Driver code
public static void main(String[] args)
{
    int arr[] = { 3, 2, 3, 2, 1 };
   
    int n = arr.length;
   
    int k = 3;
   
    findSubArray(arr, n, k);
   
}
}
  
// This code contributed by Princi Singh

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation to Find subarray
# of Length K with Maximum Peak
  
# Function to find the subarray
def findSubArray(a, n, k):
  
    # Make prefix array to store
    # the prefix sum of peak count
    pref = [0 for i in range(n)]
  
    pref[0] = 0
  
    for i in range(1, n - 1, 1):
        # Count peak for previous index
        pref[i] = pref[i - 1]
  
        # Check if this element is a peak
        if (a[i] > a[i - 1] and a[i] > a[i + 1]):
            # Increment the count
            pref[i] += 1
  
    peak = 0
    left = 0
  
    for i in range(0, n - k + 1, 1):
  
        # Check if number of peak in the sub array
        # whose l = i is greater or not
        if (pref[i + k - 2] - pref[i] > peak):
            peak = pref[i + k - 2] - pref[i]
            left = i
  
    # Print the result
    print("Left =",left + 1)
    print("Right =",left + k)
    print("Peak =",peak)
  
# Driver code
if __name__ == '__main__':
    arr = [3, 2, 3, 2, 1]
  
    n = len(arr)
    k = 3
    findSubArray(arr, n, k)
  
# This code is contributed by Surendra_Gangwar

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation to Find subarray
// of Length K with Maximum Peak
using System;
  
class GFG{
  
// Function to find the subarray
static void findSubArray(int []a, int n, int k)
{
      
    // Make prefix array to store
    // the prefix sum of peak count
    int []pref = new int[n];
      
    pref[0] = 0;
  
    for(int i = 1; i < n - 1; ++i)
    {
          
       // Count peak for previous index
       pref[i] = pref[i - 1];
         
       // Check if this element is a peak
       if (a[i] > a[i - 1] && a[i] > a[i + 1])
       {
           // Increment the count
           pref[i]++;
       }
    }
  
    int peak = 0;
    int left = 0;
      
    for(int i = 0; i + k - 1 < n; ++i)
    {
          
       // Check if number of peak in the sub array
       // whose l = i is greater or not
       if (pref[i + k - 2] - pref[i] > peak)
       {
           peak = pref[i + k - 2] - pref[i];
           left = i;
       }
    }
         
    // Print the result
    Console.Write("Left = " + (left + 1) + "\n");
    Console.Write("Right = " + (left + k) + "\n");
    Console.Write("Peak = " + peak + "\n");
}
  
// Driver code
public static void Main(String[] args)
{
    int []arr = { 3, 2, 3, 2, 1 };
    int n = arr.Length;
    int k = 3;
  
    findSubArray(arr, n, k);
}
}
  
// This code is contributed by Rohit_ranjan

chevron_right


Output:

Left = 2
Right = 4
Peak = 1

Time Complexity: O(N)

competitive-programming-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.