Simple Java solution in O(n) using a queue


  • 0
    L
    public int minSubArrayLen(int s, int[] nums) {
            Queue<Integer> queue = new LinkedList<>();
            int min=Integer.MAX_VALUE;;
            for(int i=0,sum=0;i<nums.length;) {
                sum += nums[i];
                queue.offer(nums[i]);
                while(sum>=s){
                    min = Math.min(min,queue.size());
                    sum -=queue.remove();
                }
                i++;
            }
            return min==Integer.MAX_VALUE?0:min;
        }
    

Log in to reply
 

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