![]() |
VOOZH | about |
Given an array arr[] of size N and an integer K, the task is to find the length of the largest subarray having the sum of its elements at most K, where K > 0.
Examples:
Input: arr[] = {1, 2, 1, 0, 1, 1, 0}, k = 4
Output: 5
Explanation: {1, 2, 1} => sum = 4, length = 3 {1, 2, 1, 0}, {2, 1, 0, 1} => sum = 4, length = 4 {1, 0, 1, 1, 0} =>5 sum = 3, length = 5Input: 8, 2, 4, 0, 1, 1, 0, K = 9
Output: 6
Generate all the subarrays, and keep updating the largest subarray whose sum is less than or equal to K.
5
We maintain a dynamic sized window of elements having sum less than k.
5
Time complexity is O(n) because every element goes into the window atmost once and comes out of the window at most once and both of these operations are O(1)