Maximum subarray size, such that all subarrays of that size have sum less than k

Given an array of n positive integers and a positive integer k, the task is to find the maximum subarray size such that all subarrays of that size have sum of elements less than k.

Examples :

Input :  arr[] = {1, 2, 3, 4} and k = 8.
Output : 2
Sum of subarrays of size 1: 1, 2, 3, 4.
Sum of subarrays of size 2: 3, 5, 7.
Sum of subarrays of size 3: 6, 9.
Sum of subarrays of size 4: 10.
So, maximum subarray size such that all subarrays
of that size have sum of elements less than 8 is 2.

Input :  arr[] = {1, 2, 10, 4} and k = 8.
Output : -1
There is an array element with value greater than k,
so subarray sum cannot be less than k.

Input :  arr[] = {1, 2, 10, 4} and K = 14
Output : -2



First of all, required subarray size must lie between 1 to n.

Now, since all the array element are positive integers, we can say that the prefix sum of any subarray shall be strictly increasing.
Thus, we can say that

if arr[i] + arr[i + 1] + ..... + arr[j - 1] + arr[j] <= K
then arr[i] + arr[i + 1] + ..... + arr[j - 1] <= K, as
arr[j] is a positive integer. 

So, we perform Binary Search over the range 1 to n and find the highest subarray size such that all the subarrays of that size have sum of elements less than k.

Below is implementation of this approach.

C/C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to find maximum 
// subarray size, such that all 
// subarrays of that size have 
// sum less than K.
#include<bits/stdc++.h>
using namespace std;
  
// Search for the maximum length of 
// required subarray.
int bsearch(int prefixsum[], int n, 
                             int k)
{
    // Initialize result
    int ans = -1; 
  
    // Do Binary Search for largest 
    // subarray size 
    int left = 1, right = n;
    while (left <= right)
    {
        int mid = (left + right) / 2;
  
        // Check for all subarrays after mid
        int i;
        for (i = mid; i <= n; i++)
        {
            // Checking if all the subarrays
            //  of a size less than k.
            if (prefixsum[i] - prefixsum[i - mid] > k)
                break;
        }
  
        // All subarrays of size mid have 
        // sum less than or equal to k
        if (i == n + 1)
        {
            left = mid + 1;
            ans = mid;
        }
  
        // We found a subrray of size mid 
        // with sum greater than k
        else
            right = mid - 1;
    }
    return ans;
}
  
// Return the maximum subarray size,
// such that all subarray of that size
// have sum less than K.
int maxSize(int arr[], int n, int k)
{
    // Initialize prefix sum array as 0.
    int prefixsum[n + 1];
    memset(prefixsum, 0, sizeof(prefixsum));
  
    // Finding prefix sum of the array.
    for (int i = 0; i < n; i++)
        prefixsum[i + 1] = prefixsum[i] + 
                           arr[i];
  
    return bsearch(prefixsum, n, k);
}
  
// Driver code
int main()
{
    int arr[] = {1, 2, 10, 4};
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 14;
    cout << maxSize(arr, n, k) << endl;
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to find maximum 
// subarray size, such that all 
// subarrays of that size have
// sum less than K.
import java.util.Arrays;
  
class GFG 
{
      
    // Search for the maximum length 
    // of required subarray.
    static int bsearch(int prefixsum[], 
                       int n, int k)
    {
        // Initialize result
        int ans = -1
  
        // Do Binary Search for largest 
        // subarray size
        int left = 1, right = n;
          
        while (left <= right) 
        {
            int mid = (left + right) / 2;
  
            // Check for all subarrays after mid
            int i;
            for (i = mid; i <= n; i++) 
            {
                  
                // Checking if all the subarrays 
                // of a size is less than k.
                if (prefixsum[i] - prefixsum[i - mid] > k)
                    break;
            }
  
            // All subarrays of size mid have 
            // sum less than or equal to k
            if (i == n + 1)
            {
                left = mid + 1;
                ans = mid;
            }
  
            // We found a subrray of size mid 
            // with sum greater than k
            else
                right = mid - 1;
        }
  
        return ans;
    }
  
    // Return the maximum subarray size, such 
    // that all subarray of that size have 
    // sum less than K.
    static int maxSize(int arr[], int n, int k)
    {
          
        // Initialize prefix sum array as 0.
        int prefixsum[] = new int[n + 1];
        Arrays.fill(prefixsum, 0);
  
        // Finding prefix sum of the array.
        for (int i = 0; i < n; i++)
            prefixsum[i + 1] = prefixsum[i] + arr[i];
  
        return bsearch(prefixsum, n, k);
    }
      
    // Driver code
    public static void main(String arg[])
    {
        int arr[] = { 1, 2, 10, 4 };
        int n = arr.length;
        int k = 14;
        System.out.println(maxSize(arr, n, k));
    }
}
  
// This code is contributed by Anant Agarwal.

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to find maximum 
# subarray size, such that all 
# subarrays of that size have
# sum less than K.
  
# Search for the maximum length of 
# required subarray.
def bsearch(prefixsum, n, k):
  
    # Initialize result
    # Do Binary Search for largest
    # subarray size
    ans, left, right = -1, 1, n
  
    while (left <= right):
  
        # Check for all subarrays after mid
        mid = (left + right)//2
  
        for i in range(mid, n + 1):
  
            # Checking if all the subarray of 
            # a size is less than k.
            if (prefixsum[i] - prefixsum[i - mid] > k):
                i = i - 1
                break
        i = i + 1
        if (i == n + 1):
            left = mid + 1
            ans = mid
        # We found a subrray of size mid with sum
        # greater than k
        else:
            right = mid - 1
  
    return ans;
  
# Return the maximum subarray size, such 
# that all subarray of that size have 
# sum less than K.
def maxSize(arr, n, k):
    prefixsum = [0 for x in range(n + 1)]
      
    # Finding prefix sum of the array.
    for i in range(n):
        prefixsum[i + 1] = prefixsum[i] + arr[i]
  
    return bsearch(prefixsum, n, k);
  
# Driver Code
arr = [ 1, 2, 10, 4 ]
n = len(arr)
k = 14
print (maxSize(arr, n, k))
  
# This code is contributed by Afzal

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to find maximum 
// subarray size, such that all 
// subarrays of that size have
// sum less than K.
using System;
  
class GFG {
      
    // Search for the maximum length 
    // of required subarray.
    static int bsearch(int []prefixsum, 
                          int n, int k)
    {
          
        // Initialize result
        int ans = -1; 
  
        // Do Binary Search for 
        // largest subarray size
        int left = 1, right = n;
          
        while (left <= right) 
        {
            int mid = (left + right) / 2;
  
            // Check for all subarrays 
            // after mid
            int i;
            for (i = mid; i <= n; i++) 
            {
                  
                // Checking if all the 
                // subarrays of a size is
                // less than k.
                if (prefixsum[i] - 
                     prefixsum[i - mid] > k)
                    break;
            }
  
            // All subarrays of size mid have 
            // sum less than or equal to k
            if (i == n + 1)
            {
                left = mid + 1;
                ans = mid;
            }
  
            // We found a subrray of size mid 
            // with sum greater than k
            else
                right = mid - 1;
        }
  
        return ans;
    }
  
    // Return the maximum subarray size, such 
    // that all subarray of that size have 
    // sum less than K.
    static int maxSize(int []arr, int n, int k)
    {
          
        // Initialize prefix sum array as 0.
        int []prefixsum = new int[n + 1];
        for(int i=0;i<n+1;i++)
        prefixsum[i]=0;
          
  
        // Finding prefix sum of the array.
        for (int i = 0; i < n; i++)
            prefixsum[i + 1] = prefixsum[i]
                                     + arr[i];
  
        return bsearch(prefixsum, n, k);
    }
      
    // Driver code
    public static void Main()
    {
        int []arr = { 1, 2, 10, 4 };
        int n = arr.Length;
        int k = 14;
          
        Console.Write(maxSize(arr, n, k));
    }
}
  
// This code is contributed by nitin mittal.

chevron_right



Output :

2

Time Complexity : O(n log n).

This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up

Improved By : Guibao Wang, nitin mittal