Shortest Subarray with Sum at Least K
Given an integer array nums (which may contain negatives) and an integer k, return the length of the shortest non-empty contiguous subarray whose sum is at least k. Return -1 if no such subarray exists.
Open official problem prompt ↗Find the fewest consecutive elements whose sum reaches at least k, even when negatives make simple windows fail.
You are tracking a runner's cumulative distance at each second (prefix sums). To find the shortest time span covering at least k meters, you keep a shortlist of promising start moments, ordered so earlier-and-lower readings stay and any start that is both later-recorded and no lower is thrown out because it can never beat the one before it.
- Input
- nums = [2, -1, 2], k = 3
- Output
- 3
- Why
- The whole array sums to 2 + (-1) + 2 = 3 >= k, and no shorter subarray reaches 3, so the answer is its length 3.
1 <= nums.length <= 10^5-10^5 <= nums[i] <= 10^51 <= k <= 10^9