Given an array of positive integers nums and a positive integer target, return the minimal length of a subarray whose sum is greater than or equal to target. If there is no such subarray, return 0 instead.
Input: target = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: The subarray [4,3] has the minimal length under the problem constraint.
Input: target = 4, nums = [1,4,4]
Output: 1
Input: target = 11, nums = [1,1,1,1,1,1,1,1]
Output: 0
Use a variable-size sliding window:
Since all numbers are positive, removing from left always decreases sum.
This is a Variable-Size Sliding Window problem with:
left = 0, currentSum = 0, minLen = infinitynums[right] to currentSumcurrentSum >= target:
minLen = min(minLen, right - left + 1)nums[left] from currentSumleft++minLen if found, else 01class Solution {
2 public int minSubArrayLen(int target, int[] nums) {
3 int left = 0;
4 int currentSum = 0;
5 int minLen = Integer.MAX_VALUE;
6
7 for (int right = 0; right < nums.length; right++) {
8 // Expand window: add element
9 currentSum += nums[right];
10
11 // Contract window while sum >= target
12 while (currentSum >= target) {
13 minLen = Math.min(minLen, right - left + 1);
14 currentSum -= nums[left];
15 left++;
16 }
17 }
18
19 return minLen == Integer.MAX_VALUE ? 0 : minLen;
20 }
21}
22