Open In App
Related Articles

Maximum sum subarray of size K with sum less than X

Improve Article
Improve
Save Article
Save
Like Article
Like

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 <bits/stdc++.h>
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[0]);
 
    // 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




<script>
 
// JavaScript program to implement the above approach
 
// Function to calculate maximum sum
// among all subarrays of size K
// with the sum less than X
function maxSumSubarr(A, N, K, X)
{
 
    // Initialize sum_K to 0
    let sum_K = 0;
 
    // Calculate sum of first K elements
    for (let i = 0; i < K; i++) {
 
        sum_K += A[i];
    }
 
    let 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 (let 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);
        }
    }
    document.write(Max_Sum);
}
 
// Driver Code
 
    let arr = [ -5, 8, 7, 2, 10,
                  1, 20, -4, 6, 9 ];
    let K = 5;
    let X = 30;
 
    // Size of Array
    let N = arr.length;
 
    // Function Call
    maxSumSubarr(arr, N, K, X);
     
    // This code is contributed by susmitakundugoaldanga.
</script>


Output: 

29

 

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

 


Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!

Last Updated : 19 Mar, 2021
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials