Given an array of n positive integers and a positive integer s, 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]
and s = 7
,
the subarray [4,3]
has the minimal length under the problem constraint.
Analysis:
Two pointers method, as the prefix array is already monotoic, we just keep sum[p2]-sum[p1]>=s, whenever p1 = p1+1, we move p2 correspondingly.
Solution:
1 public class Solution { 2 public int minSubArrayLen(int s, int[] nums) { 3 if (nums==null || nums.length==0) return 0; 4 int minLen = 0; 5 int p1 = 0; 6 int p2 = 1; 7 int sum = nums[p1]; 8 while (sum < s && p2<nums.length){ 9 sum += nums[p2++]; 10 } 11 if (sum<s && p2>=nums.length) return minLen; 12 minLen = p2 - p1; 13 14 while (p1<nums.length){ 15 p1++; 16 sum -= nums[p1-1]; 17 while (sum<s && p2 < nums.length){ 18 sum += nums[p2++]; 19 } 20 if (p2==nums.length && sum<s) break; 21 if (sum>=s) minLen = Math.min(p2-p1, minLen); 22 } 23 24 return minLen; 25 } 26 }