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

class Solution {
    public int minSubArrayLen(int s, int[] nums) {
         // write your code here
        int j = 0;
        int sum = 0;
        int ans = Integer.MAX_VALUE;

        for (int i = 0; i < nums.length; i++) {
            while (j < nums.length && sum < s) {
                sum = sum + nums[j];
                j++;
            }

            if (sum >= s) {
                ans = Math.min(ans, j-i);
            }
            sum -= nums[i];
        }
        if (ans == Integer.MAX_VALUE) {
            return -1;
        }
        return ans;
    }
}

results matching ""

    No results matching ""