209. Minimum Size Subarray Sum

Given an array of n positive integers and a positive integers, find the minimal length of a contiguous 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]ands = 7,
the subarray[4,3]has the minimal length under the problem constraint.

Solution:

  • left pointer start from 0;
  • right pointer traverse through the array until the sum >= s
  • update min length
    • while sum >= s, move left pointer to the next index, update the min length
public int minSubArrayLen(int s, int[] nums) {

        int left = 0;
        int min = Integer.MAX_VALUE;
        int sum = 0;
        for(int i = 0; i < nums.length; i++){
            sum += nums[i];
            if(sum < s){
                continue;
            }else{
                min = Math.min(min, i-left + 1);
                while(sum >= s && left < nums.length){
                    min = Math.min(min, i-left + 1);
                    sum -= nums[left];
                    left++;
                }
            }
        }
       if(min > nums.length){
           return 0;
       }else{
           return min;
       }
    }

results matching ""

    No results matching ""