P8 · 2 seconds · 256 MB
Longest Subarray Sum at Most K
You are given an array of **positive** integers `nums` and an integer `k`. Return the length of the longest contiguous subarray whose sum is at most `k`. If no subarray has sum ≤ `k`, return 0.
function maxLength(nums, k) → number
CONSTRAINTS
- 1 ≤ nums.length ≤ 10⁴
- 1 ≤ nums[i] ≤ 10⁴
- 0 ≤ k ≤ 10⁸
Input: nums = [2, 1, 5, 2, 3, 2, 1, 4], k = 8
Output: 4
[2, 3, 2, 1] sums to 8. No longer subarray stays ≤ 8.
Input: nums = [1, 2, 3], k = 3
Output: 2
[1, 2] sums to 3.
Input: nums = [1, 1, 1], k = 2
Output: 2
1
2
3
4
5
6
7
8
Arena judges JavaScript in a Web Worker (1s wall-clock, then TLE). Samples are public; submit runs hidden tests too. C++/Python is a later swarm package.