209. Minimum Size Subarray Sum

two pointers - fix start, move end

class Solution {
    public int minSubArrayLen(int target, int[] nums) {
        int n = nums.length;
        int sum = 0;
        int res = Integer.MAX_VALUE;
        
        int end = 0;
        for (int start = 0; start < n; start++) {
            while (end < n && sum < target) {
                sum += nums[end];
                end++;
            } // when out while end is in next position
            if (sum >= target) {
                res = Math.min(res, end - start); // so it's end - start
            }
            sum -= nums[start];
        }
        return res == Integer.MAX_VALUE ? 0 : res;
    }
}


// ask minimal length of a contiguous subarray

// sum is greater than or equal to target(positive integer)

// no result: 0

two pointers - fix end, move start (my sliding win style)

T: O(n)

S: O(1)

class Solution {
    public int minSubArrayLen(int target, int[] nums) {
        int sum = 0;
        int start = 0;
        int min = Integer.MAX_VALUE;
        for (int end = 0; end < nums.length; end++) {
            sum += nums[end];
            while (sum >= target) {
                min = Math.min(min, end - start + 1);
                sum -= nums[start];
                start++;
            }
        }
        return min == Integer.MAX_VALUE ? 0 : min;
    }
}ja

Last updated