Remove minimum elements from ends of array so that sum decreases by at least K | O ( N ) | Function to return the count of minimum elements to be removed from the ends of the array such that the sum of the array decrease by at least K ; To store the final answer ; Maximum possible sum required ; Left point ; Right pointer ; Total current sum ; Two pointer loop ; If the sum fits ; Update the answer ; Update the total sum ; Increment the left pointer ; Driver code
function minCount ( arr , n , k ) { var ans = 0 ; var sum = 0 ; for ( var i = 0 ; i < n ; i ++ ) sum += arr [ i ] ; sum -= k ; var l = 0 ; var r = 0 ; var tot = 0 ; while ( l < n ) { if ( tot <= sum ) { ans = Math . max ( ans , r - l ) ; if ( r == n ) break ; tot += arr [ r ++ ] ; } else { tot -= arr [ l ++ ] ; } } return ( n - ans ) ; } var arr = [ 1 , 11 , 5 , 5 ] ; var n = arr . length ; var k = 11 ; document . write ( minCount ( arr , n , k ) ) ;