Find the length of the shortest contiguous subarray whose sum is at least k. The array may contain negative numbers.
Given an integer array nums and an integer k, return the length of the shortest non-empty contiguous subarray whose sum is at least k.
The array can contain positive, negative, or zero values. If no such subarray exists, return -1.
This problem is tricky because a simple sliding window does not work reliably when negative numbers are allowed.
nums.k.k, or -1 if none exists.1 <= nums.lengthnums may be negative, zero, or positive.k may be positive, zero, or negative.Example 1
Input
nums = [2, -1, 2], k = 3
Output
3
Explanation
The whole array sums to 3, so the shortest valid subarray has length 3.
Example 2
Input
nums = [1, 2], k = 4
Output
-1
Explanation
No contiguous subarray has sum at least 4.
Example 3
Input
nums = [1, -1, 5, -2, 3], k = 3
Output
1
Explanation
The subarray [5] has sum 5, which is at least 3, and its length is 1.
Premium problem context
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.