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