KatInterview

Longest Subarray with Sum At Most K

Arrays & HashingAuto-graded · 17 test cases
EasyAuto-gradedArrays & Hashingarrayssliding windowprefix sums

Last updated

Tests the ability to apply a sliding window to find the longest contiguous subarray whose element sum does not exceed a given limit.

Longest Subarray with Sum At Most K

You are given a list of non-negative integers nums and a non-negative integer k.

Find the length of the longest contiguous subarray whose sum is less than or equal to k.

If no such subarray exists (i.e. even a single element exceeds k), return 0.

Constraints

  • 1 <= len(nums) <= 2000
  • 0 <= nums[i] <= 10^4
  • 0 <= k <= 10^8
  • All elements are non-negative integers (this guarantees the sliding window shrink is valid).
  • Return a single integer — the maximum length. There is exactly one correct answer.

Examples

Example 1

Input: longest_subarray_at_most_k([3, 1, 2, 4, 1], 6)

Output: 3

Example 2

Input: longest_subarray_at_most_k([1, 1, 1, 1, 1], 3)

Output: 3

Example 3

Input: longest_subarray_at_most_k([5, 6, 7], 4)

Output: 0

Hints

Hint 1

Try maintaining a window with two pointers (left and right). Expand right one step at a time, and shrink from the left whenever the window sum exceeds k.

Hint 2

Because all values are non-negative, the window sum only grows as you expand right and only shrinks as you move left — this monotonicity is what makes the sliding window correct here.

Hint 3

Track the current window sum as you move the pointers so you never need to recompute it from scratch; update the best length after every valid window.