Minimum Size Subarray Sum
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 -1 instead.
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.
Notes:
- Forward two pointers: continuous subarray
- Apply template: for-while-forward
- time: O(n)
public int minimumSize(int[] nums, int s) {
if (nums == null || nums.length == 0) {
return -1;
}
int min = Integer.MAX_VALUE;
int n = nums.length;
int j = 0;
int sum = 0;
for (int i = 0; i < n; ++i) {
while(j < n && sum < s) {
sum += nums[j];
j++;
}
if (sum >= s) {
min = Math.min(min, j-i);
}
sum -= nums[i];
if (j == n && sum < s) {
break;
}
}
return min == Integer.MAX_VALUE ? -1 : min;
}