一 穷举法
public int getMax(int[] a) {
int maxSum = 0, sum;
for (int i = 0; i < a.length; i++) {
for (int j = i; j < a.length; j++) {
sum = 0;
for (int k = i; k < j; k++) {
sum += a[k];
}
if (sum > maxSum) {
maxSum = sum;
}
}
}
return maxSum;
}
时间复杂度为:O(N^3)
二 穷举法改进
public int getMax(int[] a) {
int maxSum = 0, sum;
for (int i = 0; i < a.length; i++) {
sum = 0;
for (int j = i; j < a.length; j++) {
sum += a[j];
if (sum > maxSum) {
maxSum = sum;
}
}
}
return maxSum;
}
时间复杂度为:O(N^2)
三 分而治之法
public int getMax(int[] a, int left, int right) {
if (left == right) {
return a[left] > 0 ? a[left] : 0;
}
int center = (left + right) / 2;
int maxLeftSum = getMax(a, left, center);
int maxRightSum = getMax(a, center + 1, right);
int maxLeftBorderSum = 0, leftSum = 0;
for (int i = center; i >= left; i--) {
leftSum += a[i];
if (leftSum > maxLeftBorderSum) {
maxLeftBorderSum = leftSum;
}
}
int maxRightBorderSum = 0, rightSum = 0;
for (int i = center + 1; i <= right; i++) {
rightSum += a[i];
if (rightSum > maxRightBorderSum) {
maxRightBorderSum = rightSum;
}
}
return max(maxLeftSum, maxRightSum, maxLeftBorderSum + maxRightBorderSum);
}
private int max(int x, int y, int z) {
return x > y ? (x > z ? x : z) : (y > z ? y : z);
}
时间复杂度为:O(Nlog(N))
四 最优起点法
public int getMax(int[] a) {
int maxSum = 0, sum = 0;
for (int i = 0; i < a.length; i++) {
sum += a[i];
if (sum > maxSum) {
maxSum = sum;
} else if (sum < 0) {
sum = 0;
}
}
return maxSum;
}
时间复杂度为:O(N)