- 非递归
时间复杂度为:O(N)
class Test {
public static void main(String[] args) {
int a[] = { 1, 2, -1, 2, -4, -10, 7, -1, -9, 4, 2, -3, 5, -9 };
System.out.println(maxSubSum4(a));
}
public static int maxSubSum4(int[] a) {
int maxSum = 0, thisSum = 0;
for (int i = 0; i < a.length; i++) {
thisSum += a[i];
if (thisSum > maxSum)
maxSum = thisSum;
else if (thisSum < 0)
thisSum = 0;
}
return maxSum;
}
}
- 递归,“分治”策略
时间复杂度为:O(NlogN)
class Test {
public static void main(String[] args) {
int a[] = { 1, 2, -1, 2, -4, -10, 7, -1, -9, 4, 2, -3, 5, -9 };
System.out.println(maxSubSum3(a));
}
public static int maxSubSum3(int[] a) {
return maxSumRec(a, 0, a.length - 1);
}
public static int maxSumRec(int[] a, int left, int right) {
if (left == right)
if (a[left] > 0)
return a[left];
else
return 0;
int center = (left + right) / 2;
int maxLeftSum = maxSumRec(a, left, center);
int maxRightSum = maxSumRec(a, center + 1, right);
int maxLeftBorderSum = 0, leftBorderSum = 0;
for (int i = center; i >= left; i--) {
leftBorderSum += a[i];
if (leftBorderSum > maxLeftBorderSum)
maxLeftBorderSum = leftBorderSum;
}
int maxRightBorderSum = 0, rightBorderSum = 0;
for (int i = center + 1; i <= right; i++) {
rightBorderSum += a[i];
if (rightBorderSum > maxRightBorderSum)
maxRightBorderSum = rightBorderSum;
}
return max3(maxLeftSum, maxRightSum, maxLeftBorderSum + maxRightBorderSum);
}
public static int max3(int a, int b, int c) {
int max = a > b ? a : b;
max = max > c ? max : c;
return max;
}
}