Simple & O(n) solution


  • 0
    D
    public int minSubArrayLen(int s, int[] nums) {
        int sum = 0;
        int minLength = Integer.MAX_VALUE;
        Queue<Integer> queue = new LinkedList<>();
        for (int i = 0; i < nums.length || sum >= s;) {
            if (sum < s && i < nums.length) {
                int num = nums[i++];
                sum += num;
                queue.offer(num);
                continue;
            }
            minLength = Math.min(minLength, queue.size());
            sum -= queue.poll();
        }
        return minLength == Integer.MAX_VALUE ? 0 : minLength; 
    }

Log in to reply
 

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