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
function findSubArray ( a , n , k ) { let pref = new Array ( n ) ; pref [ 0 ] = 0 ; for ( let i = 1 ; i < n - 1 ; ++ i ) { pref [ i ] = pref [ i - 1 ] ; if ( a [ i ] > a [ i - 1 ] && a [ i ] > a [ i + 1 ] ) pref [ i ] ++ ; } let peak = 0 , left = 0 ; for ( let i = 0 ; i + k - 1 < n ; ++ i ) if ( pref [ i + k - 2 ] - pref [ i ] > peak ) { peak = pref [ i + k - 2 ] - pref [ i ] ; left = i ; } document . write ( " " + ( left + 1 ) + " " ) ; document . write ( " " + ( left + k ) + " " ) ; document . write ( " " + peak + " " ) ; } let arr = [ 3 , 2 , 3 , 2 , 1 ] ; let n = arr . length ; let k = 3 ; findSubArray ( arr , n , k ) ;