hardSliding WindowPure DSA~50 min
Shortest Subarray With Sum at Least K
Throughput readings may be negative (corrections) or positive. Find the shortest contiguous window whose total reaches a target k — a tight burst detector that tolerates dips.
Problem
Given an integer array nums (which may contain negative values) and an integer k, return the length of the shortest non-empty contiguous subarray with a sum of at least k. If no such subarray exists, return -1.
Input
An integer array nums and an integer k.
Output
An integer: the shortest qualifying length, or -1.
Constraints
- 1 <= nums.length <= 10^5
- -10^5 <= nums[i] <= 10^5
- 1 <= k <= 10^9
Examples
Example 1
Input
nums = [2,-1,2], k = 3
Output
3
The whole array sums to 3; no shorter window reaches 3.
Example 2
Input
nums = [1,2], k = 4
Output
-1
The maximum sum is 3, below 4.