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");
}
[2]
and[3]
. – Andy Turner