Given an array of integers nums and an integer k, return the length of the longest contiguous subarray whose sum is less than or equal to k.
If no such subarray exists, return 0.
Function Signature
def longest_subarray(nums: list[int], k: int) -> int:
Rules
-
A subarray is a non-empty contiguous block
nums[i..j]
with
i <= j
.
-
Elements of
nums
and the bound
k
may be negative, zero or positive.
-
The bound is inclusive: a subarray whose sum equals
k
qualifies.
-
Return
0
when every non-empty subarray has a sum greater than
k
.
Constraints
-
1 <= len(nums) <= 10^5
-
-10^4 <= nums[i] <= 10^4
-
-10^9 <= k <= 10^9
Examples
Input: nums = [1,2,3,4,5], k = 10
Output: 4
The subarray [1,2,3,4] has sum 10, which is allowed because the bound is inclusive. The full array sums to 15, which exceeds 10.
Input: nums = [3,-1,2,1,-3,4], k = 3
Output: 5
[3,-1,2,1,-3] has sum 2 and [-1,2,1,-3,4] has sum 3, so both have length 5 and fit the bound. The whole array sums to 6.
Input: nums = [5,-10,1], k = 0
Output: 3
The whole array sums to -4, which is at most 0, even though its first element alone is over the bound.