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.

分析:

这里类似于在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 == 0) return 0;
        int start = 0, total = 0;
        int minLength = Integer.MAX_VALUE;
        for (int end = 0; end < nums.length; end++) {
            total += nums[end];
            if (total >= s) {
                minLength = Math.min(minLength, end - start + 1);
            }
            while (start <= end && total - nums[start] >= s ) {
                total -= nums[start];
                start++;
                minLength = Math.min(minLength, end - start + 1);
            }
        }
        
        if (total < s) return 0;
        return minLength;
    }
}

 

posted @ 2016-07-01 05:23  北叶青藤  阅读(144)  评论(0编辑  收藏  举报