209. 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 0 instead.

For 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.

Two pointers

public class Solution {
    public int minSubArrayLen(int s, int[] nums) {
        if(nums == null || nums.length == 0) return 0;

        int len = nums.length +1;
        int start =0;
        int end = 0;
        int sum = 0;
        while(end < nums.length){// if end ever reach length, 
                                //which means start already moved to a point you need to break;
            while(sum < s && end < nums.length){
                sum += nums[end++];
            }
            while(sum >= s){
                len = Math.min(len, end - start);
                sum -= nums[start++];
            }
        }

        return len == nums.length + 1 ? 0 : len;
    }
}
public class Solution {
    public int minSubArrayLen(int s, int[] nums) {
        int len = nums.length + 1;
        int sum = 0;
        int k = 0;
        for(int i=0; i<nums.length; ){
            if (sum < s) sum += nums[i++]; // i++ has to be here , next block needs its value be updated.

            while(sum >=s){
                len = Math.min(len, i - k);
                sum -= nums[k++];
            }

        }

        return len == nums.length+1 ? 0 : len;
    }
}

results matching ""

    No results matching ""