# Maximum sum subarray of size K with sum less than X

• Difficulty Level : Easy
• Last Updated : 19 Mar, 2021

Given an array arr[] and two integers K and X, the task is to find the maximum sum among all subarrays of size K with the sum less than X.

Examples:

Input: arr[] = {20, 2, 3, 10, 5}, K = 3, X = 20
Output: 18
Explanation: Subarray of size 3 having maximum sum less than 20 is {3, 10, 5}. Therefore, required output is 18.

Input: arr[] = {-5, 8, 7, 2, 10, 1, 20, -4, 6, 9}, K = 5, X = 30
Output: 29
Explanation: Subarray of size 5having maximum sum less than 30 is {2, 10, 1, 20, -4}. Therefore, required output is 29.

Naive Approach: The simplest approach to solve the problem is to generate all subarrays of size K and check if its sum is less than X or not. Print the maximum sum obtained among all such subarrays.

Time Complexity: O(N * K)
Auxiliary Space: O(1)

Efficient Approach: Follow the steps below to solve the problem using Sliding Window technique:

1. Initialize a variable sum_K to store the sum of first K array elements.
2. If sum_K is less than X, then initialize Max_Sum with sum_K.
3. Traverse the array from (K + 1)th index and perform the following:
1. In each iteration, subtract the first element of the previous K length subarray and add the current element to sum_K.
2. If sum_K is less than X, then compare sum_K with Max_Sum and update Max_Sum accordingly.
4. Finally, print Max_Sum.

Below is the implementation of the above approach:

## C++

 `// C++ program for the above approach``#include ``using` `namespace` `std;` `// Function to calculate maximum sum``// among all subarrays of size K``// with the sum less than X``void` `maxSumSubarr(``int` `A[], ``int` `N,``                  ``int` `K, ``int` `X)``{` `    ``// Initialize sum_K to 0``    ``int` `sum_K = 0;` `    ``// Calculate sum of first K elements``    ``for` `(``int` `i = 0; i < K; i++) {` `        ``sum_K += A[i];``    ``}` `    ``int` `Max_Sum = 0;` `    ``// If sum_K is less than X``    ``if` `(sum_K < X) {` `        ``// Initialize MaxSum with sum_K``        ``Max_Sum = sum_K;``    ``}` `    ``// Iterate over the array from``    ``// (K + 1)-th index``    ``for` `(``int` `i = K; i < N; i++) {` `        ``// Subtract the first element``        ``// from the previous K elements``        ``// and add the next element``        ``sum_K -= (A[i - K] - A[i]);` `        ``// If sum_K is less than X``        ``if` `(sum_K < X) {` `            ``// Update the Max_Sum``            ``Max_Sum = max(Max_Sum, sum_K);``        ``}``    ``}` `    ``cout << Max_Sum << endl;``}` `// Driver Code``int` `main()``{``    ``int` `arr[] = { -5, 8, 7, 2, 10,``                  ``1, 20, -4, 6, 9 };``    ``int` `K = 5;``    ``int` `X = 30;` `    ``// Size of Array``    ``int` `N = ``sizeof``(arr)``            ``/ ``sizeof``(arr);` `    ``// Function Call``    ``maxSumSubarr(arr, N, K, X);` `    ``return` `0;``}`

## Java

 `// Java program for the above approach``import` `java.io.*;` `class` `GFG{``    ` `// Function to calculate maximum sum``// among all subarrays of size K``// with the sum less than X``private` `static` `void` `maxSumSubarr(``int` `A[], ``int` `N,``                                 ``int` `K, ``int` `X)``{``    ` `    ``// Initialize sum_K to 0``    ``int` `sum_K = ``0``;``    ` `    ``// Calculate sum of first K elements``    ``for``(``int` `i = ``0``; i < K; i++)``    ``{``        ``sum_K += A[i];``    ``}``    ` `    ``int` `Max_Sum = ``0``;``    ` `    ``// If sum_K is less than X``    ``if` `(sum_K < X)``    ``{``        ` `        ``// Initialize MaxSum with sum_K``        ``Max_Sum = sum_K;``    ``}``    ` `    ``// Iterate over the array from``    ``// (K + 1)-th index``    ``for``(``int` `i = K; i < N; i++)``    ``{``        ` `        ``// Subtract the first element``        ``// from the previous K elements``        ``// and add the next element``        ``sum_K -= (A[i - K] - A[i]);``        ` `        ``// If sum_K is less than X``        ``if` `(sum_K < X)``        ``{``            ` `            ``// Update the Max_Sum``            ``Max_Sum = Math.max(Max_Sum, sum_K);``        ``}``    ``}``    ` `    ``System.out.println(Max_Sum);``}`` ` `// Driver Code``public` `static` `void` `main (String[] args)``{``    ``int` `arr[] = { -``5``, ``8``, ``7``, ``2``, ``10``,``                  ``1``, ``20``, -``4``, ``6``, ``9` `};``    ``int` `K = ``5``;``    ``int` `X = ``30``;``    ` `    ``// Size of Array``    ``int` `N = arr.length;``    ` `    ``// Function Call``    ``maxSumSubarr(arr, N, K, X);``}``}` `// This code is contributed by jithin`

## Python3

 `# Python3 program for the above approach`` ` `# Function to calculate maximum sum``# among all subarrays of size K``# with the sum less than X``def` `maxSumSubarr(A, N, K, X):``    ` `    ``# Initialize sum_K to 0``    ``sum_K ``=` `0`` ` `    ``# Calculate sum of first K elements``    ``for` `i ``in` `range``(``0``, K):``        ``sum_K ``+``=` `A[i]``    ` `    ``Max_Sum ``=` `0`` ` `    ``# If sum_K is less than X``    ``if` `(sum_K < X):`` ` `        ``# Initialize MaxSum with sum_K``        ``Max_Sum ``=` `sum_K``    ` `    ``# Iterate over the array from``    ``# (K + 1)-th index``    ``for` `i ``in` `range``(K, N):`` ` `        ``# Subtract the first element``        ``# from the previous K elements``        ``# and add the next element``        ``sum_K ``-``=` `(A[i ``-` `K] ``-` `A[i])`` ` `        ``# If sum_K is less than X``        ``if` `(sum_K < X):``            ` `            ``# Update the Max_Sum``            ``Max_Sum ``=` `max``(Max_Sum, sum_K)``        ` `    ``print``(Max_Sum)` `# Driver Code``arr ``=` `[ ``-``5``, ``8``, ``7``, ``2``, ``10``,``         ``1``, ``20``, ``-``4``, ``6``, ``9` `]``K ``=` `5``X ``=` `30`` ` `# Size of Array``N ``=` `len``(arr)`` ` `# Function Call``maxSumSubarr(arr, N, K, X)` `# This code is contributed by sanjoy_62`

## C#

 `// C# program for the above approach``using` `System;` `class` `GFG{``    ` `// Function to calculate maximum sum``// among all subarrays of size K``// with the sum less than X``private` `static` `void` `maxSumSubarr(``int` `[]A, ``int` `N,``                                 ``int` `K, ``int` `X)``{``    ` `    ``// Initialize sum_K to 0``    ``int` `sum_K = 0;``    ` `    ``// Calculate sum of first K elements``    ``for``(``int` `i = 0; i < K; i++)``    ``{``        ``sum_K += A[i];``    ``}``    ` `    ``int` `Max_Sum = 0;``    ` `    ``// If sum_K is less than X``    ``if` `(sum_K < X)``    ``{``        ` `        ``// Initialize MaxSum with sum_K``        ``Max_Sum = sum_K;``    ``}``    ` `    ``// Iterate over the array from``    ``// (K + 1)-th index``    ``for``(``int` `i = K; i < N; i++)``    ``{``        ` `        ``// Subtract the first element``        ``// from the previous K elements``        ``// and add the next element``        ``sum_K -= (A[i - K] - A[i]);``        ` `        ``// If sum_K is less than X``        ``if` `(sum_K < X)``        ``{``            ` `            ``// Update the Max_Sum``            ``Max_Sum = Math.Max(Max_Sum, sum_K);``        ``}``    ``}``    ``Console.WriteLine(Max_Sum);``}`` ` `// Driver Code``public` `static` `void` `Main(String[] args)``{``    ``int` `[]arr = { -5, 8, 7, 2, 10,``                   ``1, 20, -4, 6, 9 };``    ``int` `K = 5;``    ``int` `X = 30;``    ` `    ``// Size of Array``    ``int` `N = arr.Length;``    ` `    ``// Function Call``    ``maxSumSubarr(arr, N, K, X);``}``}` `// This code is contributed by Amit Katiyar`

## Javascript

 ``

Output:

`29`

Time Complexity: O(N)
Auxiliary Space: O(1)

My Personal Notes arrow_drop_up