Guru Level
Implement the shortestSubarrayAtLeastKLength method that returns the shortest subarray length with sum at least k.
You are given an integer array that may contain positive, zero, and negative values. Return the length of the shortest continuous subarray whose sum is at least k.
If no such subarray exists, return -1. Because negative values are allowed, a normal two-pointer window is not enough.
Use prefix sums and a monotonic deque.
For each prefix sum, check whether subtracting the smallest useful previous prefix gives a sum of at least k. When it does, update the answer and remove that previous prefix because a later prefix can give a shorter length.
Maintain the deque in increasing order of prefix sums. If the current prefix is smaller than or equal to the last stored prefix, the last one is no longer useful.
Pseudocode:
function shortestSubarrayAtLeastKLength(nums, size, k):
prefix[0] = 0
for i from 0 to size - 1:
prefix[i + 1] = prefix[i] + nums[i]
deque = empty deque of indexes
answer = infinity
for i from 0 to size:
while deque is not empty and prefix[i] - prefix[deque.front] >= k:
answer = min(answer, i - deque.front)
remove front from deque
while deque is not empty and prefix[i] <= prefix[deque.back]:
remove back from deque
add i to back of deque
if answer is infinity:
return -1
return answer