Maximize length of subarray of equal elements by performing at most K increment operations | Function to find the maximum length of subarray of equal elements after performing at most K increments ; Stores the size of required subarray ; Starting point of a window ; Stores the sum of window ; Iterate over array ; Current element ; Remove index of minimum elements from deque which are less than the current element ; Insert current index in deque ; Update current window sum ; Calculate required operation to make current window elements equal ; If cost is less than k ; Shift window start pointer towards right and update current window sum ; Return answer ; Driver Code ; Length of array
function maxSubarray ( a , k , n ) { var answer = 0 ; var start = 0 ; var s = 0 ; var dq = [ ] ; for ( var i = 0 ; i < n ; i ++ ) { var x = a [ i ] ; while ( dq . length != 0 && a [ dq [ 0 ] ] <= x ) dq . shift ( ) ; dq . push ( i ) ; s += x ; var cost = a [ dq [ 0 ] ] * ( answer + 1 ) - s ; if ( cost <= k ) answer ++ ; else { if ( dq [ 0 ] == start ) dq . shift ( ) ; s -= a [ start ++ ] ; } } return answer ; } var a = [ 2 , 2 , 4 ] ; var k = 10 ; var n = a . length ; document . write ( maxSubarray ( a , k , n ) ) ;