Maximum sum subarray of size K with sum less than X | C ++ program for the above approach ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void maxSumSubarr ( int A [ ] , int N , int K , int X ) { int sum_K = 0 ; for ( int i = 0 ; i < K ; i ++ ) { sum_K += A [ i ] ; } int Max_Sum = 0 ; if ( sum_K < X ) { Max_Sum = sum_K ; } for ( int i = K ; i < N ; i ++ ) { sum_K -= ( A [ i - K ] - A [ i ] ) ; if ( sum_K < X ) { Max_Sum = max ( Max_Sum , sum_K ) ; } } cout << Max_Sum << endl ; } int main ( ) { int arr [ ] = { -5 , 8 , 7 , 2 , 10 , 1 , 20 , -4 , 6 , 9 } ; int K = 5 ; int X = 30 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; maxSumSubarr ( arr , N , K , X ) ; return 0 ; }