Shortest Subarray with Sum at Least K
Problem statement
Given an integer array nums and an integer k, return the length of the shortest nonempty contiguous subarray whose sum is at least k. Return -1 if no such subarray exists.
Values may be negative. A subarray is a contiguous part of the array.
Function
shortestSubarray(nums: int[], k: int) → intExamples
Example 1
nums = [1]k = 1return = 1The single-element subarray has sum 1.
Example 2
nums = [1,2]k = 4return = -1Even the sum of the entire array is below 4.
Example 3
nums = [2,-1,2]k = 3return = 3Only the entire array reaches a sum of 3.
Constraints
1 <= nums.length <= 100000.-100000 <= nums[i] <= 100000.1 <= k <= 10^9.