Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Maximum subarray size having all subarrays sums less than k
Next article icon

Maximum subarray size having all subarrays sums less than k

Last Updated : 07 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array of positive integers arr[] of size n, and an integer k. The task is to find the maximum subarray size such that all subarrays of that size have sum less than or equals to k.

Examples : 

Input : arr[] = [1, 2, 3, 4], k = 8.
Output : 2
Explanation: Following are the sum of subarray of size 1 to 4.

  • 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 the sum of elements less than 8 is 2.

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

Input : arr[] = [1, 2, 10, 4], k = 14
Output : 2

Table of Content

  • [Naive Approach] - Using Nested Loops - O(n ^ 3) Time and O(1) Space
  • [Better Approach] - Using Binary Search and Sliding Window - O(n * log n) Time and O(1) Space
  • [Expected Approach] - Using Sliding Window - O(n) Time and O(1) Space

[Naive Approach] - Using Nested Loops - O(n ^ 3) Time and O(1) Space

The idea is to generate all possible subarrays of all sizes and find sum of their elements. To do so, use three nested loops, where the outer most loops marks the size of the subarray, the middle loop marks the starting index of the subarray, and the inner loops marks the last index of the subarray.
For any integer x in range [1, n], if all the subarrays of array arr[] of size x, has sum of there elements less than or equals to k, store the value x in answer and move to x + 1. At last print the result.

C++
#include <bits/stdc++.h> using namespace std;  // Function to find the maximum subarray // size such that all subarrays of that // size have sum less than or equals to k. int maxSubarraySize(vector<int> &arr, int k) {     int n = arr.size();      // to store the answer     int ans = -1;          // generate all possible subarrays     for(int i = 1; i <= n; i++) {          // to store the max sum of all          // possible subarrays of size i         int maxSum = INT_MIN;          for(int j = 0; j < n - i + 1; j++) {              // calculate the sum of the subarray             int sum = 0;             for(int l = j; l < j + i; l++) {                 sum += arr[l];             }              // update the max sum             maxSum = max(maxSum, sum);         }          // if the maxSum is less than or equals to k         if(maxSum <= k) {             ans = max(ans, i);         }     }      return ans; }  int main() {     vector<int> arr = {1, 2, 3, 4};     int k = 8;     cout << maxSubarraySize(arr, k) << endl;     return 0; } 
Java
// Function to find the maximum subarray // size such that all subarrays of that // size have sum less than or equals to k. import java.util.*;  class GfG {      // Function to find the maximum subarray     // size such that all subarrays of that     // size have sum less than or equals to k.     static int maxSubarraySize(int[] arr, int k) {         int n = arr.length;                  // to store the answer         int ans = -1;                  // generate all possible subarrays         for (int i = 1; i <= n; i++) {                          // to store the max sum of all              // possible subarrays of size i             int maxSum = Integer.MIN_VALUE;                          for (int j = 0; j < n - i + 1; j++) {                                  // calculate the sum of the subarray                 int sum = 0;                 for (int l = j; l < j + i; l++) {                     sum += arr[l];                 }                                  // update the max sum                 maxSum = Math.max(maxSum, sum);             }                          // if the maxSum is less than or equals to k             if (maxSum <= k) {                 ans = Math.max(ans, i);             }         }         return ans;     }          public static void main(String[] args) {         int[] arr = {1, 2, 3, 4};         int k = 8;         System.out.println(maxSubarraySize(arr, k));     } } 
Python
# Function to find the maximum subarray # size such that all subarrays of that # size have sum less than or equals to k. def maxSubarraySize(arr, k):     n = len(arr)          # to store the answer     ans = -1          # generate all possible subarrays     for i in range(1, n + 1):                  # to store the max sum of all          # possible subarrays of size i         maxSum = float('-inf')                  for j in range(0, n - i + 1):                          # calculate the sum of the subarray             sum = 0             for l in range(j, j + i):                 sum += arr[l]                          # update the max sum             maxSum = max(maxSum, sum)                  # if the maxSum is less than or equals to k         if maxSum <= k:             ans = max(ans, i)     return ans  if __name__ == "__main__":     arr = [1, 2, 3, 4]     k = 8     print(maxSubarraySize(arr, k)) 
C#
// Function to find the maximum subarray // size such that all subarrays of that // size have sum less than or equals to k. using System; using System.Collections.Generic;  class GfG {      // Function to find the maximum subarray     // size such that all subarrays of that     // size have sum less than or equals to k.     static int maxSubarraySize(int[] arr, int k) {         int n = arr.Length;                  // to store the answer         int ans = -1;                  // generate all possible subarrays         for (int i = 1; i <= n; i++) {                          // to store the max sum of all              // possible subarrays of size i             int maxSum = int.MinValue;                          for (int j = 0; j < n - i + 1; j++) {                                  // calculate the sum of the subarray                 int sum = 0;                 for (int l = j; l < j + i; l++) {                     sum += arr[l];                 }                                  // update the max sum                 maxSum = Math.Max(maxSum, sum);             }                          // if the maxSum is less than or equals to k             if (maxSum <= k) {                 ans = Math.Max(ans, i);             }         }         return ans;     }          static void Main() {         int[] arr = {1, 2, 3, 4};         int k = 8;         Console.WriteLine(maxSubarraySize(arr, k));     } } 
JavaScript
// Function to find the maximum subarray // size such that all subarrays of that // size have sum less than or equals to k. function maxSubarraySize(arr, k) {     let n = arr.length;          // to store the answer     let ans = -1;          // generate all possible subarrays     for (let i = 1; i <= n; i++) {                  // to store the max sum of all          // possible subarrays of size i         let maxSum = -Infinity;                  for (let j = 0; j < n - i + 1; j++) {                          // calculate the sum of the subarray             let sum = 0;             for (let l = j; l < j + i; l++) {                 sum += arr[l];             }                          // update the max sum             maxSum = Math.max(maxSum, sum);         }                  // if the maxSum is less than or equals to k         if (maxSum <= k)             ans = Math.max(ans, i);     }     return ans; }   let arr = [1, 2, 3, 4]; let k = 8; console.log(maxSubarraySize(arr, k)); 

Output
2 

[Better Approach] - Using Binary Search and Sliding Window - O(n * log n) Time and O(1) Space

It can be observed that if for any integer x, all subarrays of size x have the sum of there elements less than or equals to k, then x - 1 will also satisfy the condition. Similarly, if x does not satisfy the condition then x + 1 will also not work. Thus we can apply binary search in range 1 to n, to find the max integer x that satisfies the required condition.

Follow the below given steps to solve the problem:

  • Create two counters, low and high, and set their values to 1 and n respectively.
  • Now run a loop until low <= high
  • In each iteration, find the mid of low and high, i.e. (low + high) / 2.
  • Now using sliding window approach, find the maximum possible sum of a subarray of size mid.
  • If maxSum <= k, then set low = mid + 1, as we can increase the size of subarray.
  • Else, if maxSum > k, then set high = mid - 1, as we need to reduce the size of subarray.
  • The loop breaks when low > high, and high stores the final result.
C++
#include <bits/stdc++.h> using namespace std;  // Function to find the maximum subarray // size such that all subarrays of that // size have sum less than or equals to k. int maxSubarraySize(vector<int> &arr, int k) {     int n = arr.size();      // initialize the low and high pointers     int low = 1, high = n;      // perform binary search      while(low <= high) {         int mid = low + (high - low) / 2;          // to store the sum of the subarray         int sum = 0;          // to store the max sum of all          // possible subarrays of size mid         int maxSum = INT_MIN;          for(int i = 0; i < n; i++) {             sum += arr[i];              if(i >= mid) {                 sum -= arr[i - mid];             }              if(i >= mid - 1) {                 maxSum = max(maxSum, sum);             }         }          if(maxSum <= k)             low = mid + 1;         else             high = mid - 1;     }      if(high == 0)         return -1;     return high; }  int main() {     vector<int> arr = {1, 2, 3, 4};     int k = 8;     cout << maxSubarraySize(arr, k) << endl;     return 0; } 
Java
// Function to find the maximum subarray // size such that all subarrays of that // size have sum less than or equals to k. import java.util.*;  class GfG {      // Function to find the maximum subarray     // size such that all subarrays of that     // size have sum less than or equals to k.     static int maxSubarraySize(int[] arr, int k) {         int n = arr.length;                  // initialize the low and high pointers         int low = 1, high = n;                  // perform binary search          while(low <= high) {             int mid = low + (high - low) / 2;                          // to store the sum of the subarray             int sum = 0;                          // to store the max sum of all              // possible subarrays of size mid             int maxSum = Integer.MIN_VALUE;                          for(int i = 0; i < n; i++) {                 sum += arr[i];                                  if(i >= mid) {                     sum -= arr[i - mid];                 }                                  if(i >= mid - 1) {                     maxSum = Math.max(maxSum, sum);                 }             }                          if(maxSum <= k)                 low = mid + 1;             else                 high = mid - 1;         }                  if(high == 0)             return -1;         return high;     }          public static void main(String[] args) {         int[] arr = {1, 2, 3, 4};         int k = 8;         System.out.println(maxSubarraySize(arr, k));     } } 
Python
# Function to find the maximum subarray # size such that all subarrays of that # size have sum less than or equals to k. def maxSubarraySize(arr, k):     n = len(arr)          # initialize the low and high pointers     low = 1     high = n          # perform binary search      while low <= high:         mid = low + (high - low) // 2                  # to store the sum of the subarray         sum_val = 0                  # to store the max sum of all          # possible subarrays of size mid         maxSum = -float('inf')                  for i in range(n):             sum_val += arr[i]                          if i >= mid:                 sum_val -= arr[i - mid]                          if i >= mid - 1:                 maxSum = max(maxSum, sum_val)                  if maxSum <= k:             low = mid + 1         else:             high = mid - 1          if high == 0:         return -1     return high  if __name__ == "__main__":     arr = [1, 2, 3, 4]     k = 8     print(maxSubarraySize(arr, k)) 
C#
// Function to find the maximum subarray // size such that all subarrays of that // size have sum less than or equals to k. using System; using System.Collections.Generic;  class GfG {      // Function to find the maximum subarray     // size such that all subarrays of that     // size have sum less than or equals to k.     static int maxSubarraySize(int[] arr, int k) {         int n = arr.Length;                  // initialize the low and high pointers         int low = 1, high = n;                  // perform binary search          while (low <= high) {             int mid = low + (high - low) / 2;                          // to store the sum of the subarray             int sum = 0;                          // to store the max sum of all              // possible subarrays of size mid             int maxSum = int.MinValue;                          for (int i = 0; i < n; i++) {                 sum += arr[i];                                  if (i >= mid) {                     sum -= arr[i - mid];                 }                                  if (i >= mid - 1) {                     maxSum = Math.Max(maxSum, sum);                 }             }                          if (maxSum <= k)                 low = mid + 1;             else                 high = mid - 1;         }                  if (high == 0)             return -1;         return high;     }          static void Main() {         int[] arr = {1, 2, 3, 4};         int k = 8;         Console.WriteLine(maxSubarraySize(arr, k));     } } 
JavaScript
// Function to find the maximum subarray // size such that all subarrays of that // size have sum less than or equals to k. function maxSubarraySize(arr, k) {     let n = arr.length;          // initialize the low and high pointers     let low = 1, high = n;          // perform binary search      while (low <= high) {         let mid = low + Math.floor((high - low) / 2);                  // to store the sum of the subarray         let sum = 0;                  // to store the max sum of all          // possible subarrays of size mid         let maxSum = -Infinity;                  for (let i = 0; i < n; i++) {             sum += arr[i];                          if (i >= mid) {                 sum -= arr[i - mid];             }                          if (i >= mid - 1) {                 maxSum = Math.max(maxSum, sum);             }         }                  if (maxSum <= k)             low = mid + 1;         else             high = mid - 1;     }          if (high === 0)         return -1;     return high; }  let arr = [1, 2, 3, 4]; let k = 8; console.log(maxSubarraySize(arr, k)); 

Output
2 

[Expected Approach] - Using Sliding Window - O(n) Time and O(1) Space

The approach is to find the minimum subarray size whose sum is greater than integer k. Out result will be this window size - 1.

  • Create two counters, start and end, to store the starting and ending point of the current subarray.
  • Also create two variables, sum and minLen, to store the sum of current subarray and the minimum length of subarray with sum of its elements greater than k respectively.
  • Initialize start and end with 0
  • Now, run a loop until end < n, and in each iteration add arr[end] to sum and increment end by 1.
  • While sum > k, store the minimum of minLen and end - start, subtract arr[start] from sum, and increment start by 1.
  • The loop breaks when end >= n, and minLen - 1 is the final answer.
C++
#include <bits/stdc++.h> using namespace std;  // Function to find the maximum subarray // size such that all subarrays of that // size have sum less than or equals to k. int maxSubarraySize(vector<int> &arr, int k) {     int n = arr.size();      // to store the start and end      // point of the subarray     int start = 0, end = 0;      // to store the sum of subarray     int sum = 0;      // to store the minimum size of     // subarray with sum greater than k     int minLen = n + 1;      // using sliding window technique     // to find the subarray     while(end < n) {          // add the current element to the sum         // and increase the end pointer         sum += arr[end];         end++;          // if the sum is greater than k         while(sum > k) {             minLen = min(minLen, end - start);             sum -= arr[start];             start++;         }     }      int ans = minLen - 1;      if(ans == 0)         return -1;     return ans; }  int main() {     vector<int> arr = {1, 2, 3, 4};     int k = 8;     cout << maxSubarraySize(arr, k) << endl;     return 0; } 
Java
// Function to find the maximum subarray // size such that all subarrays of that // size have sum less than or equals to k. import java.util.*;  class GfG {      // Function to find the maximum subarray     // size such that all subarrays of that     // size have sum less than or equals to k.     static int maxSubarraySize(int[] arr, int k) {         int n = arr.length;                  // to store the start and end          // point of the subarray         int start = 0, end = 0;                  // to store the sum of subarray         int sum = 0;                  // to store the minimum size of         // subarray with sum greater than k         int minLen = n + 1;                  // using sliding window technique         // to find the subarray         while(end < n) {                          // add the current element to the sum             // and increase the end pointer             sum += arr[end];             end++;                          // if the sum is greater than k             while(sum > k) {                 minLen = Math.min(minLen, end - start);                 sum -= arr[start];                 start++;             }         }                  int ans = minLen - 1;                  if(ans == 0)             return -1;         return ans;     }          public static void main(String[] args) {         int[] arr = {1, 2, 3, 4};         int k = 8;         System.out.println(maxSubarraySize(arr, k));     } } 
Python
# Function to find the maximum subarray # size such that all subarrays of that # size have sum less than or equals to k. def maxSubarraySize(arr, k):     n = len(arr)          # to store the start and end      # point of the subarray     start = 0     end = 0          # to store the sum of subarray     sum_val = 0          # to store the minimum size of     # subarray with sum greater than k     minLen = n + 1          # using sliding window technique     # to find the subarray     while end < n:                  # add the current element to the sum         # and increase the end pointer         sum_val += arr[end]         end += 1                  # if the sum is greater than k         while sum_val > k:             minLen = min(minLen, end - start)             sum_val -= arr[start]             start += 1          ans = minLen - 1          if ans == 0:         return -1     return ans  if __name__ == "__main__":     arr = [1, 2, 3, 4]     k = 8     print(maxSubarraySize(arr, k)) 
C#
// Function to find the maximum subarray // size such that all subarrays of that // size have sum less than or equals to k. using System; using System.Collections.Generic;  class GfG {      // Function to find the maximum subarray     // size such that all subarrays of that     // size have sum less than or equals to k.     static int maxSubarraySize(int[] arr, int k) {         int n = arr.Length;                  // to store the start and end          // point of the subarray         int start = 0, end = 0;                  // to store the sum of subarray         int sum = 0;                  // to store the minimum size of         // subarray with sum greater than k         int minLen = n + 1;                  // using sliding window technique         // to find the subarray         while (end < n) {                          // add the current element to the sum             // and increase the end pointer             sum += arr[end];             end++;                          // if the sum is greater than k             while (sum > k) {                 minLen = Math.Min(minLen, end - start);                 sum -= arr[start];                 start++;             }         }                  int ans = minLen - 1;                  if (ans == 0)             return -1;         return ans;     }          static void Main() {         int[] arr = {1, 2, 3, 4};         int k = 8;         Console.WriteLine(maxSubarraySize(arr, k));     } } 
JavaScript
// Function to find the maximum subarray // size such that all subarrays of that // size have sum less than or equals to k. function maxSubarraySize(arr, k) {     let n = arr.length;          // to store the start and end      // point of the subarray     let start = 0, end = 0;          // to store the sum of subarray     let sum = 0;          // to store the minimum size of     // subarray with sum greater than k     let minLen = n + 1;          // using sliding window technique     // to find the subarray     while (end < n) {                  // add the current element to the sum         // and increase the end pointer         sum += arr[end];         end++;                  // if the sum is greater than k         while (sum > k) {             minLen = Math.min(minLen, end - start);             sum -= arr[start];             start++;         }     }          let ans = minLen - 1;          if (ans === 0)         return -1;     return ans; }  let arr = [1, 2, 3, 4]; let k = 8; console.log(maxSubarraySize(arr, k)); 

Output
2 

Next Article
Maximum subarray size having all subarrays sums less than k

K

kartik
Improve
Article Tags :
  • DSA
  • Arrays
  • Binary Search
  • prefix-sum
  • subarray
  • subarray-sum
Practice Tags :
  • Arrays
  • Binary Search
  • prefix-sum

Similar Reads

    First subarray having sum at least half the maximum sum of any subarray of size K
    Given an array arr[] and an integer K, the task is to find the first subarray which has a sum greater than or equal to half of the maximum possible sum from any subarray of size K. Examples: Input: arr[] = {2, 4, 5, 1, 4, 6, 6, 2, 1, 0}, K = 3 Output: 6 2 1 Explanation: The given array has a maximum
    9 min read
    Maximize the subarray sum by choosing M subarrays of size K
    Given an array arr containing N positive integers, and two integers K and M, the task is to calculate the maximum sum of M subarrays of size K. Example: Input: arr[] = {1, 2, 1, 2, 6, 7, 5, 1}, M = 3, K = 2Output: 33Explanation: The three chosen subarrays are [2, 6], [6, 7] and [7, 5] respectively.
    6 min read
    Maximum sum subarray having sum less than given sum using Set
    Given an array arr[] of length N and an integer K, the task is the find the maximum sum subarray with a sum less than K.Note: If K is less than the minimum element, then return INT_MIN. Examples: Input: arr[] = {-1, 2, 2}, K = 4 Output: 3 Explanation: The subarray with maximum sum which is less than
    7 min read
    Maximum sum subarray having sum less than or equal to given sum
    You are given an array of non-negative integers and a target sum. Your task is to find a contiguous subarray whose sum is the maximum possible, while ensuring that it does not exceed the given target sum.Note: The given array contains only non-negative integers.Examples: Input: arr[] = [1, 2, 3, 4,
    6 min read
    Maximum sum subarray of size K with sum less than X
    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 = 20Output: 18Explanation: Subarray of size 3 having maximum sum less than 20 is {3, 10, 5}. Therefore, requ
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences