Minimum Size Subarray Sum

Posted 北叶青藤

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
    }
}

 

以上是关于Minimum Size Subarray Sum的主要内容,如果未能解决你的问题,请参考以下文章

#Leetcode# 209. Minimum Size Subarray Sum

Minimum Size Subarray Sum

Minimum Size Subarray Sum

leetcode 209. Minimum Size Subarray Sum

Minimum Size Subarray Sum

Minimum Size Subarray Sum -- leetcode