Shortest Subarray with Sum at Least K

Given an integer array nums and an integer k, return the length of the shortest non-empty subarray with sum at least k. If there is no such subarray, return -1. Example: Input: nums = [2,-1,2], k = 3 Output: 3 Explanation: The whole array has sum 3 and is the shortest valid subarray. Pattern focus: Monotonic Deque for prefix-sum optimization.

Input Format

nums = array of integers, k = minimum required sum

Output Format

length of the shortest valid subarray, or -1 if none exists

Constraints

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

Examples

Example 1:

Input:

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

Output:

3

Explanation:

The only valid subarray is the full array.

Example 2:

Input:

nums = [1]
k = 1

Output:

1

Explanation:

A single element can already satisfy the requirement.

Loading...
Shortest Subarray with Sum at Least K