Maximum Continuous without start and end indexes
// Mon Dec 3 19:21:34 2018
// -1, 2, -1, 4
public static int continuousSum(int[] arr){
int max = 0;
if(arr != null){
int len = arr.length;
int cur = 0;
for(int i=0; i< len; i++){
if(cur < 0)
cur = 0;
cur = cur + arr[i];
// compare: [curr value, curr accumulator, max]
max = Math.max(max, arr[i]);
max = Math.max(max, cur);
}
}
return max;
}
Maximum Continuous Sum, Simple and easy one
/**
Given a integer array, find the maximum continuous sum
1 3 -4 5 -1 6
1 => 1
1 3 => 4
1 3 -4 => 0
1 3 -4 5 => 5
1 3 -4 5 -1 => 4
1 3 -4 5 -1 6 => 10
1 3 -6 5 -1 6
1 => 1 m = 1, max = 1
1 3 => 4 m = 4, max = 4
1 3 -6 => -2 m = 0 max = 4
1 3 -6 5 => 5 m = 5, max = 5
1 3 -6 5 -1 => m = 4, max = 5
1 3 -6 5 -1 6 m = 10 max = 10
*/
public static Integer maxSumArray(Integer[] arr){
int m = 0, max = 0;
for(int i = 0; i < arr.length; i++){
m += arr[i];
if (m < 0){
m = 0;
}
if(max < m){
max = m;
}
}
return max;
}
Maximum Continuous Sum in a List
1. Find the maximum continuous sum from a list
2. Find the start index and end index
// Mon Dec 3 21:45:59 2018
// only work when not all elem are negative
//
// Sun Sep 25 18:03:40 PDT 2016
// Fix bug: start gets the wrong index
//
static int maxList(Integer[] arr) {
int tmp_start = 0;
int end = 0;
int start = 0;
int max = 0;
int sum = 0;
for(int i=0; i 0) {
int m = Math.max(arr[i], sum + arr[i]);
if(m > max) {
max = m;
start = tmp_start;
end = i;
}
sum += arr[i];
} else {
sum = 0;
}
}
Print.p("start[" + start + "]");
Print.p("end [" + end + "]");
return max;
}
1. Find the maximum continuous sum from a list
2. All the elements maybe be negative
// Test file: /Users/cat/myfile/bitbucket/javalib/Aron.java
public static int negativeContinuousSum(int[] arr){
if(arr != null && arr.length > 0){
int len = arr.length;
int currmax = arr[0];
int maxsofar = arr[0];
for(int i=1; i< len; i++){
maxsofar = Math.max(arr[i], maxsofar + arr[i]);
currmax = Math.max(currmax, maxsofar);
}
return currmax;
}
throw new IllegalArgumentException("Argument is not valid.");
}