问题描述:
有一串数字(可正可负的int,放在数组Num里),要求找到起始位置start和终止位置end,使得从start位置到end位置的所有数字之和最大,返回这个最大值max。
算法思想:使用动态规划。
设 f[x] 为以 a[x] 终止且包含 a[x] 的最大序列的和,有:
f[1] = a[1];
f[x+1] = f[x] > 0 ? f[x] + a[x+1] : a[x+1]
那么最大子序列的和就是 f[1] .. f[n] 中最大的一个。其算法的时间复杂度为O(n),代码实现如下:
void maxSubse(int[] a, int length) {
int start, resultBegin, resultEnd;
int max, resultMax;
int i;
start = resultBegin = resultEnd = 0;
max = resultMax = a[0];
for(i = 1; i < length; i++) {
if (max > 0) {
max += a[i];
}
else {
max = a[i];
start = i;
}
if (max > resultMax) {
resultMax = max;
resultStart = start;
resultEnd = i;
}
}
}