0
votes

I have an array[1,2,3] and sum as 4. so all the continous sub arrays are [1],[1,2][2,3] ans [1,2,3]. So the max length subarray less than or equal to sum is [1,2]and the length is 2.

I have approached in a the following way to find all the subarrays and to check the sum of the subarrays as below. But this approach is not working with negative numbers. {1,2,1,1,3,-2,-3,7,9}; - Ans : 7

 private static void maximumSubArray(int[] a, int sum) {

    int start = 0;
    int end =0;
    int mylen =-1;
    int subarrSum =0;
    for(int i=0;i<a.length;i++){
        subarrSum += a[i];
        end++;
        while(subarrSum > sum){
            subarrSum-= a[start];
            start +=1;

        }

        mylen = Math.max(mylen, end-start);
    }
    System.out.println(mylen + "  -- My len");

}
1
"Is there any better approach.??" Yes. You can search in linear time.Andy Turner
"so all the continous sub arrays are" You forgot [2] and [3].Andy Turner

1 Answers

0
votes

This is a variation of the classical maximum contiguous subarray problem. You can use dynamic programming (memorization) to solve this problem. Try something like this:

private static void maximumSubArray(int[] a, long sum, int maxLen) {
    long maximumSoFar = Long.MIN_VALUE;
    long maximumEndingHere = Long.MIN_VALUE;
    for (int i = 0; i < a.length; i++) {
        // if you're inside the array beyond maxLen, start dropping off the previous start element
        int prevStart = i >= maxLen ? a[i - maxLen] : 0;
        maximumEndingHere = Math.max(a[i], maximumEndingHere + a[i] - prevStart);
        if (maximumEndingHere > maximumSoFar && maximumEndingHere <= sum) {
            maximumSoFar = maximumEndingHere;
        } else if (a[i] > maximumSoFar && a[i] <= sum) {
            maximumSoFar = a[i];
        } else if (maximumEndingHere > sum) {
            maximumEndingHere -= prevStart;
        }
    }
    System.out.println(maximumSoFar);
}

If I had some more time, I'd write the logic inside for loop in a cleaner way, but this should work and it works in O(n) time.