Leetcode 209: Minimum Size Subarray Sum
Minimum Size Subarray SumTotal Accepted:1954Total Submissions:8526
Given an arrayNPositive integers and a positive integerS, Find the minimal length of a subarray of which the sum ≥S. If there isn't one, return 0 instead.
For example, given the array[2,3,1,2,4,3]Ands = 7,
The subarray[4,3]Has the minimal length under the problem constraint.
[Idea]
Two pointers, start end and end, go backward until sum is greater than s. Then start is backward until sum is less than s. min value is updated at the same time.
public class Solution { //1,1,4 public int minSubArrayLen(int s, int[] nums) { //init check int start = 0; int end = 0; int sum = 0; int min = Integer.MAX_VALUE; while(start=s && start<=end) { min = Math.min(min, end-start); sum -= nums[start++]; } } return min==Integer.MAX_VALUE ? 0 : min; }}