给定由n个整数(可能为负数)组成的序列 a1 , a2 , ... , an,求该序列形如 for k = i to j : sum = sum + ak : next k的子段和的最大值.
算法:动态规划。递推式如下:
b[j] = max(sum(i,j)) 1<=i<=b
b[j] = max(b[j-1] + a[j], a[j])
代码如下:
int max(int a, int b)
{
return a > b? a : b;
}
int maxsum(int *a, int n)
{
int max_sum;
int *b = new int[n+1];
b[0] = 0;
for (int ii = 1; ii <= n; ii++)
{
b[ii] = max(b[ii-1] + a[ii-1], a[ii-1]);
}
max_sum = b[1];
for(int jj = 1; jj <= n; jj++)
{
if (b[jj] > max_sum)
{
max_sum = b[jj];
}
}
delete [] b;
return max_sum;
}
int main()
{
int a[] = {-1, 1, 2, 3, -4, 6, -1, 4};
int ret = maxsum(a, 8);
cout<<ret<<endl;
return 0;
}