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
def maxSumSubarr ( A , N , K , X ) : NEW_LINE INDENT sum_K = 0 NEW_LINE for i in range ( 0 , K ) : NEW_LINE INDENT sum_K += A [ i ] NEW_LINE DEDENT Max_Sum = 0 NEW_LINE if ( sum_K < X ) : NEW_LINE INDENT Max_Sum = sum_K NEW_LINE DEDENT for i in range ( K , N ) : NEW_LINE INDENT sum_K -= ( A [ i - K ] - A [ i ] ) NEW_LINE if ( sum_K < X ) : NEW_LINE INDENT Max_Sum = max ( Max_Sum , sum_K ) NEW_LINE DEDENT DEDENT print ( Max_Sum ) NEW_LINE DEDENT arr = [ - 5 , 8 , 7 , 2 , 10 , 1 , 20 , - 4 , 6 , 9 ] NEW_LINE K = 5 NEW_LINE X = 30 NEW_LINE N = len ( arr ) NEW_LINE maxSumSubarr ( arr , N , K , X ) NEW_LINE