Example Input: -1,2,6,4,-4,-5,56,78,-2,9
Desired Output: 134
public int MaxSumOfSubArray(int... input) {
int size = input.length;
int max = 0;
boolean isIn = false;
int current_sum = 0;
int previous = -1;
for(int i=0; i<size; i++) {
if(!isIn) current_sum = 0;
if(input[i]>=0) {
isIn = true;
current_sum = current_sum+input[i];
} else if(previous>=0 && max<current_sum) {
max = current_sum;
isIn = false;
}
previous = input[i];
}
return max;
}
Monday, February 15, 2016
Sunday, February 14, 2016
Rotate an Array
public int[] rotate(int count, int... input) {
for(int i=0; i<count; i++) {
input = rotate(input);
}
return input;
}
private int[] rotate(int... input) {
int s = input.length-1;
int[] output = new int[input.length];
for(int j=0; j < s; j++) {
output[j+1]=input[j];
}
output[0]=input[s];
return output;
}
for(int i=0; i<count; i++) {
input = rotate(input);
}
return input;
}
private int[] rotate(int... input) {
int s = input.length-1;
int[] output = new int[input.length];
for(int j=0; j < s; j++) {
output[j+1]=input[j];
}
output[0]=input[s];
return output;
}
Subscribe to:
Posts (Atom)