Find the length of the shortest contiguous subarray whose sum is at least k. The array may contain negative numbers.
Shortest Subarray With Sum at Least K
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.
Input Format
- A single integer array
nums. - A single integer
k.
Output Format
- Return an integer: the minimum length of a non-empty contiguous subarray with sum at least
k, or-1if none exists.
Constraints
1 <= nums.length- Elements of
numsmay be negative, zero, or positive. kmay be positive, zero, or negative.- Find the shortest valid contiguous subarray.
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.
Show 1 more example
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
Unlock deeper context for this problem
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.