Short Java solution


  • 0
    R

    Using sliding window algorithm. A tricky part is that min is initialized to s. This works because in the worst case all the nums are equal to 1 and it would require s numbers to sum up to s. This approach will work even when the input is Integer.MAX_VALUE and the array is of size Integer.MAX_VALUE that contains all 1s (pretty unlikely scenario though).

    public int minSubArrayLen(int s, int[] nums) {
        int lo = 0, sum = 0, min = s;
        for (int i = 0; i<nums.length; i++) {
            sum+=nums[i];
            while (lo<i && sum - nums[lo] >= s) {
                sum-= nums[lo++];
            }
            min = (sum>=s) ? Math.min(min, i - lo + 1) : min;
        }
        return (lo != 0 || nums.length>=s || min < s) ? min : 0;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.