Short Easy Java Solution, O(n) time complexity


  • 1
    S

    Keep on adding the numbers, when the sum becomes greater than 's', remove the 'last recently added' element and keep checking if sum is greater than or equal to 's'. Every time it is greater than equal to 's', record the length of the window. Let me know if someone has any doubts.

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

Log in to reply
 

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