Skip to content

Instantly share code, notes, and snippets.

@junminstorage
Last active December 5, 2015 01:41
Show Gist options
  • Save junminstorage/13833f0a60ac296f7091 to your computer and use it in GitHub Desktop.
Save junminstorage/13833f0a60ac296f7091 to your computer and use it in GitHub Desktop.
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.
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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment