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.
分析:
这里类似于在array上面放一个window, window的左边从第一个数开始,增加window的size, 保证window里的数之和大于S,然后每当window 右边往前走一步(window变大),就check是否可以把window左边cover的值remove掉(window 变小),并同时update minLength.
public class Solution {
public int minSubArrayLen(int s, int[] nums) {
if (nums == null || nums.length == ) return ;
int start = , total = ;
int minLength = Integer.MAX_VALUE;
for (int end = ; end < nums.length; end++) {
total += nums[end];
if (total >= s) {
minLength = Math.min(minLength, end - start + );
}
while (start <= end && total - nums[start] >= s ) {
total -= nums[start];
start++;
minLength = Math.min(minLength, end - start + );
}
} if (total < s) return ;
return minLength;
}
}