Example 1
- Input
- target = 7, nums = [2,3,1,2,4,3]
- Output
- 2
The subarray [4,3] sums to 7 with length 2, and no length-1 subarray reaches 7.
Given an array of positive integers and a target sum, return the smallest length of a contiguous subarray whose elements add up to at least the target, or 0 when no such subarray exists.
Given an array of positive integers nums and a positive integer target, return the minimal length of a contiguous subarray whose sum is greater than or equal to target. If there is no such subarray, return 0.
Positivity is the whole trick: extending a window can only raise its sum and shrinking it can only lower it, so test shorter windows by shrinking while the target is still reached, then expand again when the sum falls below it. For target = 7 and nums = [2,3,1,2,4,3] the answer is 2 from [4,3].
1 <= target <= 10^91 <= nums.length <= 10^51 <= nums[i] <= 10^4The subarray [4,3] sums to 7 with length 2, and no length-1 subarray reaches 7.
The single element [4] reaches the target, so the answer is 1.
The whole array sums to 8, below 11, so no valid subarray exists.
Only the whole array reaches 6. Removing either endpoint drops the sum below target, so the answer is the full length 3.
A valid interval reaches at least target, but we want the shortest one. All numbers are positive: adding a rightmost number raises the sum, and removing a leftmost number lowers it. In Example 1, [2,3,1,2] reaches 8, so record length 4 and remove 2; the remaining sum 6 is too small. Repeating this expand-then-shrink process eventually finds [4,3], sum 7 and length 2.
Reveal Brute Force: intuition, complexity, and code
target the window is valid.target: no window ever validates and the answer is 0.target, such as target = 4 with [1,4,4]: the window shrinks to length 1 immediately.if instead of a while: one expansion can allow several left moves, and the skipped lengths may include the true minimum.For sum goals over positive numbers, expand until valid then shrink while valid: monotonic sums make one pass enough for the shortest window.