chau
BAN USER
Comments (3)
Reputation 0
Page:
1
Comment hidden because of low score. Click to expand.
Comment hidden because of low score. Click to expand.
0
of 0 vote
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 subarray 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("subarray based0 index [from  to]:[" + start + "  " + max + "]");
}
}

chau
August 29, 2012 Comment hidden because of low score. Click to expand.
Page:
1
CareerCup is the world's biggest and best source for software engineering interview preparation. See all our resources.
 chau August 29, 2012