862. Shortest Subarray with Sum at Least K
Practice Shortest Subarray with Sum at Least K for free on NudgeCode: Hard, Sliding Window pattern. Write it in Python or JavaScript, run the tests in your browser, and ask for a hint when you are stuck.
Given an integer array nums, which may contain negative numbers, and a positive integer k, return the length of the shortest non-empty contiguous subarray whose sum is at least k. Return -1 if no subarray reaches k.
Because of the negative numbers, making a window longer can make its sum smaller, so a plain sliding window doesn't work here.
Example
nums = [2,-1,2], k = 3 -> 3
nums = [1,2], k = 4 -> -1
In the first case only the whole array sums to 3.
Constraints
- 1 <= nums.length <= 10^5
- -10^5 <= nums[i] <= 10^5
- 1 <= k <= 10^9