chau
BAN USER
Here is my solution. Notice that there might be more than one sub arrays on the solution. This solution just take the last one found largest sub-array that satisfy the question (i.e. the one with start index largest). If you want to keep all of them, use HashMap<Integer,Integer> to keep the start/end index pairs of the matched.
public static void main( String ... args) {
int arr[]= { -2, -3, 4, -1, -2, 1, 5, -3, 2, -2, -3, 6, -1, -2, 1, 5, -3, 2};
largestSubArrayMatchSum(arr, 2);
}
public static void largestSubArrayMatchSum( int[] arr, int num) {
int sum = 0;
int i = 0;
int max = 0;
int start= 0;
int j = 0;
while( j < arr.length) {
sum += arr[i];
if( sum >= num) {
if( sum == num) {
int prev = max;
max = Math.max(max, i );
if( max > prev) {
start = j;
}
};
}
++i;
if( i == arr.length) {
++j;
i = 0;
}
}
if( max != 0) {
//Found.
System.out.println("sub-array based-0 index [from - to]:[" + start + " - " + max + "]");
}
}
- chau August 29, 2012