![]() |
VOOZH | about |
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
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.
2
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:
2
The approach is to find the minimum subarray size whose sum is greater than integer k. Out result will be this window size - 1.
2