Friday, December 4, 2015

Minimum Size Subarray Sum

This is a leetCode problem: http://www.programcreek.com/2014/05/leetcode-minimum-size-subarray-sum-java/

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 of 2 under the problem constraint.

We can solve this by a sliding window, aka inch worm algorithm. Essentially we grow this sliding window to the right if the sum is smaller than the s, once sum >= s, then we update the minimal length of the window and then start to shrink the window from the left until sum < s. Here is the code:




public static int minimumSizeArray(int[] nums, int s){
int min = Integer.MAX_VALUE, sum = 0;
int p1=0,p2=0,len=nums.length;
while(p2<len && p1<len){
sum += nums[p2];
while(p1<len && sum >=s){
min = Math.min(p2-p1+1, min);
sum -= nums[p1];
p1++;
}
p2++;
}
return min == Integer.MAX_VALUE?0 :min;
}

No comments:

Post a Comment