Problem · Array
Longest Subarray with Sum at Most K
Learn this problemProblem statement
Given an integer array nums and an integer k, return the maximum length of a non-empty contiguous subarray whose sum is at most k.
The array may contain positive, zero, and negative values, so a standard positive-only sliding window is not sufficient.
Return 0 when no non-empty subarray satisfies the limit.
Function
longestSubarrayAtMostK(nums: int[], k: long) → intExamples
Example 1
nums = [1,2,-1,2]k = 3return = 3The subarray [1, 2, -1] has sum 2 and length 3. The full array has sum 4.
Example 2
nums = [5,-10,5]k = 0return = 3The entire array sums to 0; the negative value makes the longest valid window non-monotonic.
Constraints
1 <= nums.length <= 200000-10^9 <= nums[i] <= 10^9-10^14 <= k <= 10^14- Subarray sums fit in a signed 64-bit integer.