最大连续子序列之和
给定整数A1,A2,A3,...,An(可能为负整数),求最大的连续子序列和。如果所有数是负数,则和是零。
例如:{-2,11,-4,13,-5,2} 答案是20,序列项从第2项到第4项。
此题很多解法,现讨论4种解法。第1种是简单穷举搜索算法,效率特别低。第2种算法是第一种算法的改进,简单观察完成。第3种算法非常高效,但不简单,复杂度是线性的O(n)。第4种算法复杂度是O(N log N)
-
public static int maxSumRec(int[] a, int left, int right)
-
{
-
int maxLeftBorderSum = 0, maxRightBorderSum = 0;
-
int leftBorderSum = 0, rightBorderSum = 0;
-
int center = (left + right) / 2;
-
-
if (left == right)
-
{
-
return a[left] > 0 ? a[left] : 0;
-
}
-
-
int maxLeftSum = maxSumRec(a, left, center);
-
int maxRightSum = maxSumRec(a, center + 1, right);
-
-
for (int i = center; i >= left; i--)
-
{
-
leftBorderSum += a[i];
-
if (leftBorderSum > maxLeftBorderSum)
-
maxLeftBorderSum = leftBorderSum;
-
}
-
-
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 maxLeftSum, int maxRightSum, int maxSum)
-
{
-
return maxLeftSum > maxRightSum ? (maxLeftSum > maxSum ? maxLeftSum
-
: maxSum) : (maxRightSum > maxSum ? maxRightSum : maxSum);
-
}
-
-
public static int maxSubsequenceSum(int[] a)
-
{
-
return a.length > 0 ? maxSumRec(a, 0, a.length - 1) : 0;
-
}
