VOOZH about

URL: https://www.geeksforgeeks.org/dsa/longest-subarray-sum-elements-atmost-k/

⇱ Longest subarray having sum of elements atmost K - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Longest subarray having sum of elements atmost K

Last Updated : 3 Oct, 2024

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 = 5

Input: 8, 2, 4, 0, 1, 1, 0, K = 9
Output: 6

Naive Approach - O(n^2) Time and O(1) Space

Generate all the subarrays, and keep updating the largest subarray whose sum is less than or equal to K.


Output
5

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

We maintain a dynamic sized window of elements having sum less than k.

  1. Keep adding elements while the current sum is less than or equal to k. Keep updating result also if required.
  2. Whenever sum becomes more than k, keep removing elements while the sum is more than k.
  3. IF we find an element greater than k, we reset the window size as 0 and sum as 0.

Output
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)

Comment