Skip to content
Related Articles

Related Articles

Improve Article

Maximum length L such that the sum of all subarrays of length L is less than K

  • Difficulty Level : Hard
  • Last Updated : 12 Apr, 2021

Given an array of length N and an integer K. The task is to find the maximum length L such that all the subarrays of length L have sum of its elements less than K.
Examples: 
 

Input: arr[] = {1, 2, 3, 4, 5}, K = 20 
Output:
The only subarray of length 5 is the complete 
array and (1 + 2 + 3 + 4 + 5) = 15 < 20.
Input: arr[] = {1, 2, 3, 4, 5}, K = 10 
Output:
 

 

Approach: For maximum sum of a subarray of length K, go through the approach discussed in this article. Now, binary search can be performed to find the maximum length. As the array elements are positive then increasing the subarray length will increase the maximum sum of the subarray elements for that length.
Below is the implementation of the above approach: 
 

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the maximum sum
// in a subarray of size k
int maxSum(int arr[], int n, int k)
{
    // k must be greater
    if (n < k) {
        return -1;
    }
 
    // Compute sum of first window of size k
    int res = 0;
    for (int i = 0; i < k; i++)
        res += arr[i];
 
    // Compute sums of remaining windows by
    // removing first element of previous
    // window and adding last element of
    // current window.
    int curr_sum = res;
    for (int i = k; i < n; i++) {
        curr_sum += arr[i] - arr[i - k];
        res = max(res, curr_sum);
    }
 
    return res;
}
 
// Function to return the length of subarray
// Sum of all the subarray of this
// length is less than or equal to K
int solve(int arr[], int n, int k)
{
    int max_len = 0, l = 0, r = n, m;
 
    // Binary search from l to r as all the
    // array elements are positive so that
    // the maximum subarray sum is monotonically
    // increasing
    while (l <= r) {
        m = (l + r) / 2;
 
        // Check if the subarray sum is
        // greater than K or not
        if (maxSum(arr, n, m) > k)
            r = m - 1;
        else {
            l = m + 1;
 
            // Update the maximum length
            max_len = m;
        }
    }
    return max_len;
}
 
// Driver code
int main()
{
    int arr[] = { 1, 2, 3, 4, 5 };
    int n = sizeof(arr) / sizeof(int);
    int k = 10;
 
    cout << solve(arr, n, k);
 
    return 0;
}

Java




// Java implementation of the approach
class GFG
{
     
    // Function to return the maximum sum
    // in a subarray of size k
    static int maxSum(int arr[], int n, int k)
    {
        // k must be greater
        if (n < k)
        {
            return -1;
        }
     
        // Compute sum of first window of size k
        int res = 0;
        for (int i = 0; i < k; i++)
            res += arr[i];
     
        // Compute sums of remaining windows by
        // removing first element of previous
        // window and adding last element of
        // current window.
        int curr_sum = res;
        for (int i = k; i < n; i++)
        {
            curr_sum += arr[i] - arr[i - k];
            res = Math.max(res, curr_sum);
        }
     
        return res;
    }
     
    // Function to return the length of subarray
    // Sum of all the subarray of this
    // length is less than or equal to K
    static int solve(int arr[], int n, int k)
    {
        int max_len = 0, l = 0, r = n, m;
     
        // Binary search from l to r as all the
        // array elements are positive so that
        // the maximum subarray sum is monotonically
        // increasing
        while (l <= r)
        {
            m = (l + r) / 2;
     
            // Check if the subarray sum is
            // greater than K or not
            if (maxSum(arr, n, m) > k)
                r = m - 1;
            else
            {
                l = m + 1;
     
                // Update the maximum length
                max_len = m;
            }
        }
        return max_len;
    }
     
    // Driver code
    public static void main (String[] args)
    {
        int arr[] = { 1, 2, 3, 4, 5 };
        int n = arr.length;
         
        int k = 10;
     
        System.out.println(solve(arr, n, k));
    }
}
 
// This code is contributed by AnkitRai01

Python3




# Python3 implementation of the approach
 
# Function to return the maximum sum
# in a subarray of size k
def maxSum(arr, n, k) :
 
    # k must be greater
    if (n < k) :
        return -1;
 
    # Compute sum of first window of size k
    res = 0;
     
    for i in range(k) :
        res += arr[i];
 
    # Compute sums of remaining windows by
    # removing first element of previous
    # window and adding last element of
    # current window.
    curr_sum = res;
     
    for i in range(k, n) :
        curr_sum += arr[i] - arr[i - k];
        res = max(res, curr_sum);
 
    return res;
 
# Function to return the length of subarray
# Sum of all the subarray of this
# length is less than or equal to K
def solve(arr, n, k) :
 
    max_len = 0; l = 0; r = n;
 
    # Binary search from l to r as all the
    # array elements are positive so that
    # the maximum subarray sum is monotonically
    # increasing
    while (l <= r) :
        m = (l + r) // 2;
 
        # Check if the subarray sum is
        # greater than K or not
        if (maxSum(arr, n, m) > k) :
            r = m - 1;
        else :
            l = m + 1;
 
            # Update the maximum length
            max_len = m;
             
    return max_len;
 
# Driver code
if __name__ == "__main__" :
 
    arr = [ 1, 2, 3, 4, 5 ];
    n = len(arr);
    k = 10;
 
    print(solve(arr, n, k));
 
# This code is contributed by AnkitRai01

C#




// C# implementation of the approach
using System;
 
class GFG
{
     
    // Function to return the maximum sum
    // in a subarray of size k
    static int maxSum(int []arr, int n, int k)
    {
        // k must be greater
        if (n < k)
        {
            return -1;
        }
     
        // Compute sum of first window of size k
        int res = 0;
        for (int i = 0; i < k; i++)
            res += arr[i];
     
        // Compute sums of remaining windows by
        // removing first element of previous
        // window and adding last element of
        // current window.
        int curr_sum = res;
        for (int i = k; i < n; i++)
        {
            curr_sum += arr[i] - arr[i - k];
            res = Math.Max(res, curr_sum);
        }
        return res;
    }
     
    // Function to return the length of subarray
    // Sum of all the subarray of this
    // length is less than or equal to K
    static int solve(int []arr, int n, int k)
    {
        int max_len = 0, l = 0, r = n, m;
     
        // Binary search from l to r as all the
        // array elements are positive so that
        // the maximum subarray sum is monotonically
        // increasing
        while (l <= r)
        {
            m = (l + r) / 2;
     
            // Check if the subarray sum is
            // greater than K or not
            if (maxSum(arr, n, m) > k)
                r = m - 1;
            else
            {
                l = m + 1;
     
                // Update the maximum length
                max_len = m;
            }
        }
        return max_len;
    }
     
    // Driver code
    public static void Main ()
    {
        int []arr = { 1, 2, 3, 4, 5 };
        int n = arr.Length;
         
        int k = 10;
     
        Console.WriteLine(solve(arr, n, k));
    }
}
 
// This code is contributed by AnkitRai01

Javascript




<script>
 
// javascript implementation of the approach
 
// Function to return the maximum sum
// in a subarray of size k
    function maxSum(arr , n , k) {
        // k must be greater
        if (n < k) {
            return -1;
        }
 
        // Compute sum of first window of size k
        var res = 0;
        for (i = 0; i < k; i++)
            res += arr[i];
 
        // Compute sums of remaining windows by
        // removing first element of previous
        // window and adding last element of
        // current window.
        var curr_sum = res;
        for (i = k; i < n; i++) {
            curr_sum += arr[i] - arr[i - k];
            res = Math.max(res, curr_sum);
        }
 
        return res;
    }
 
    // Function to return the length of subarray
    // Sum of all the subarray of this
    // length is less than or equal to K
    function solve(arr , n , k) {
        var max_len = 0, l = 0, r = n, m;
 
        // Binary search from l to r as all the
        // array elements are positive so that
        // the maximum subarray sum is monotonically
        // increasing
        while (l <= r) {
            m = parseInt((l + r) / 2);
 
            // Check if the subarray sum is
            // greater than K or not
            if (maxSum(arr, n, m) > k)
                r = m - 1;
            else {
                l = m + 1;
 
                // Update the maximum length
                max_len = m;
            }
        }
        return max_len;
    }
 
    // Driver code
     
        var arr = [ 1, 2, 3, 4, 5 ];
        var n = arr.length;
 
        var k = 10;
 
        document.write(solve(arr, n, k));
 
// This code contributed by Rajput-Ji
 
</script>
Output: 
2

 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :