Find the shortest contiguous subarray whose sum is at least a target value.
Given an array of positive integers and a target sum, determine the minimum length of any contiguous subarray whose elements add up to at least the target. If no such subarray exists, return 0.
You are looking for a contiguous slice of the array, not a subsequence. Because all numbers are positive, the sum of a window changes in a predictable way as you expand or shrink it.
Input Format
- An integer
target. - An integer array
numsof positive integers.
Output Format
Return the minimum length of a contiguous subarray whose sum is at least target. If no valid subarray exists, return 0.
Constraints
1 <= nums.length1 <= nums[i]1 <= target- The array contains only positive integers.
Example 1
Input
target = 7, nums = [2,3,1,2,4,3]
Output
2
Explanation
The subarray [4,3] has sum 7 and length 2, which is the minimum possible.
Example 2
Input
target = 4, nums = [1,4,4]
Output
1
Explanation
The single element [4] already reaches the target, so the answer is 1.
Show 1 more example
Example 3
Input
target = 11, nums = [1,1,1,1,1,1,1,1]
Output
0
Explanation
No contiguous subarray reaches a sum of 11.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.