Min Size Subarray Sum
ID:209
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.Idea
Code
public int minSubArrayLen(int target, int[] nums) {
int res = Integer.MAX_VALUE;
int left = 0, right = 0;
int sum = 0;
while(right<nums.length)
{
sum += nums[right];
while(sum-nums[left]>=target){ // shrink left
sum-=nums[left];
left++;
}
if(sum>=target)
{
res = Math.min(res, right - left+1);
}
right++;
}
return res == Integer.MAX_VALUE?0:res;
}Last updated