Shortest Subarray with Sum at Least K

Hard

Description

Given an integer array nums and an integer k, return the length of the shortest non-empty subarray of nums with a sum of at least k. If there is no such subarray, return -1.

Examples

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

The entire array sums to 3.

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

Works with negative numbers.

Input:nums = [1, 4, -3, 7, 2], k = 8
Output:2
Explanation:

The shortest subarray with sum ≥ 8 is [7, 2] with length 2 and sum 9. Other valid subarrays include [1, 4, -3, 7] (length 4, sum 9) and [4, -3, 7, 2] (length 4, sum 10), but they are longer.

Constraints

  • 1 ≤ nums.length ≤ 10^5
  • -10^5 ≤ nums[i] ≤ 10^5
  • 1 ≤ k ≤ 10^9

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!