Maximum sum subarray of size K with sum less than X | Function to calculate maximum sum among all subarrays of size K with the sum less than X ; Initialize sum_K to 0 ; Calculate sum of first K elements ; If sum_K is less than X ; Initialize MaxSum with sum_K ; Iterate over the array from ( K + 1 ) - th index ; Subtract the first element from the previous K elements and add the next element ; If sum_K is less than X ; Update the Max_Sum ; Driver Code ; Size of Array ; Function Call
function maxSumSubarr ( A , N , K , X ) { let sum_K = 0 ; for ( let i = 0 ; i < K ; i ++ ) { sum_K += A [ i ] ; } let Max_Sum = 0 ; if ( sum_K < X ) { Max_Sum = sum_K ; } for ( let i = K ; i < N ; i ++ ) { sum_K -= ( A [ i - K ] - A [ i ] ) ; if ( sum_K < X ) { Max_Sum = Math . max ( Max_Sum , sum_K ) ; } } document . write ( Max_Sum ) ; } let arr = [ - 5 , 8 , 7 , 2 , 10 , 1 , 20 , - 4 , 6 , 9 ] ; let K = 5 ; let X = 30 ; let N = arr . length ; maxSumSubarr ( arr , N , K , X ) ;