我想为给定的整数输入数组找到一个非空的连续子数组,它可以有重复的值。我尝试了分而治之的方法来找到一个数组的最大连续子数组,它按预期返回不同的结果。请在下面找到代码。
private static int maxSumRec(int[] a, int low, int high) {
int leftSum = 0, rightSum = 0;
int sum = 0;
if (low == high) { // Base case
return a[low];
}
int mid = (low + high) >> 1; // (low + high) / 2
int maxLeftSum = maxSumRec(a, low, mid);
int maxRightSum = maxSumRec(a, mid + 1, high);
//max-crossing-subarray
for (int i = mid; i >= low; i--) {
sum += a[i];
if (sum > leftSum) {
leftSum = sum;
}
}
sum = 0;
for (int i = mid + 1; i <= high; i++) {
sum += a[i];
if (sum > rightSum) {
rightSum = sum;
}
}
return max3(maxLeftSum, maxRightSum, (leftSum + rightSum));
}
private static int max3(int a, int b, int c) {
return a > b ? (a > c ? a : c) : (b > c ? b : c);
}
public static void main(String[] args) {
//INPUT
int a[] = {
-5, 71, 23, 41, 34, 1, 3, 6, 2, 91, 312, 42, 31, 67, 12, 10, 18, 56, 90, 21, 45, 47, 89, 1999999990,
78, -7, 76, 75, 74, 73, 72, 80, 24, 25, 61, 69, 84, 0, -1, 145, 1902, 200, 199, 198, 197, 196, 195, 194,
78, 77, 76, 75, 74, 73, 72, 80, 24, 25, 61, 69, 84, 0, -1, 145, 1902, 200, 199, 198, 197, 196, 195, 194,
5, 71, 23, 41, 34, 1, 3, 6, 2, 91, 312, 42, 31, 67, 12, 10, 18, 56, 90, 21, 45, 47, 89, 1999999990
};
int maxSum = maxSumRec(a, 0, a.length - 1);
System.out.println("Max sum is " + maxSum);
}
此代码将结果返回为2000005400。MCS 的非递归版本返回一个不同的结果,即2000010721,它是从 {1-94} 找到的。我无法弄清楚原因。请让我知道代码中是否存在错误。