vamsu
7/28/2018 - 7:46 PM

Find length of smallest sub array greater than given sum

Find length of smallest sub array greater than given sum

import java.util.*;
public class ClosestSumGreaterThanGiven {
    public static void main(String args[]) {
        ClosestSumGreaterThanGiven closestSum = new ClosestSumGreaterThanGiven();
        int[][] input = {
          null,
          {},
          {1},
          {0,1,11,3,1,3,4},
          {1,2,3,4,5,6},
          {10,4,2,5,6,3,8,1}
        };
        
        for(int i=0; i< input.length; i++) {
            int sum = 10;
            System.out.println("Input: " + Arrays.toString(input[i]) + ", sum=" + sum +" Result: " + closestSum.find(input[i], sum));
        }
    }
    
    private int find(int[] input, int sum) {
        if(input == null || input.length < 1) {
            return -1;
        }
        int windowSum = 0;
        int minLen = Integer.MAX_VALUE;
        int start = 0;
        for(int end =0; end <input.length; end++) {
            windowSum += input[end];
            if(windowSum < 0) {
                windowSum = 0;
                start = end;
            }
            while(windowSum > sum && start <= end) {
                minLen = Math.min(minLen, end-start+1); 
                windowSum -= input[start++];
            }
        }
        return minLen;
    }
}