Longest Subarray with Sum At Most K
Arrays & HashingAuto-graded · 17 test casesLast 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) <= 20000 <= nums[i] <= 10^40 <= 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.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Key Insight
Because every element is non-negative, the sum of a window [left, right] is monotonically non-decreasing as right grows and monotonically non-increasing as left grows. This monotonicity is the prerequisite for a correct sliding window: we can always decide whether to expand or shrink in O(1) per step.
Algorithm
- Maintain two pointers
leftandright, both starting at index 0. - Iterate
rightfrom 0 ton-1. At each step, addnums[right]tocurrent_sum. - While
current_sum > k, subtractnums[left]and advanceleft. - After the inner while-loop, the window
[left, right]is guaranteed to have a sum ≤ k. Updatebest = max(best, right - left + 1). - Return
best.
Correctness
- The inner while-loop always terminates because in the worst case
leftreachesrightand the window becomes a single elementnums[right]. If even that single element exceedsk, the window length is 0 (left overtakes right, window is empty with sum 0 ≤ k). - Every possible valid window is considered: whenever we shrink we do so only because the current window is invalid, and we never skip a window of maximum length.
Complexity
- Time: O(n) — each pointer moves at most n steps, so at most 2n iterations total.
- Space: O(1) — only a constant number of variables are maintained.
from typing import List
def longest_subarray_at_most_k(nums: List[int], k: int) -> int:
left = 0
current_sum = 0
best = 0
for right in range(len(nums)):
current_sum += nums[right]
# Shrink from the left while the window sum exceeds k
while current_sum > k and left <= right:
current_sum -= nums[left]
left += 1
# At this point the window [left, right] is valid (sum <= k)
best = max(best, right - left + 1)
return best