Shortest Subarray with Sum at Least K

Hard Topics Company Tags

Return the smallest length of a nonempty contiguous subarray of nums whose sum is at least k. If no such subarray exists, return -1. Values in nums may be negative.

Example 1:

Input: nums = [3,-2,5]
k = 4

Output: 1

Explanation: The single-element subarray [5] already has sum at least 4, so the shortest length is 1.

Example 2:

Input: nums = [2,-1,2]
k = 3

Output: 3

Explanation: The full array has sum 3. Each shorter contiguous subarray has sum below 3, so the answer is 3.

Example 3:

Input: nums = [-2,-1]
k = 1

Output: -1

Explanation: Every nonempty subarray has a negative sum. None can reach the positive target 1, so return -1.

Constraints:

  • 1 <= nums.length <= 100000
  • -100000 <= nums[i] <= 100000
  • 1 <= k <= 1000000000


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.