求数组a的最大字段和
定义一个数组b
b[i]表示截止到第i个数的最大字段和
那么我们知道如果b[i-1]<=0,b[i]的值应该为a[i]
如果b[i-1]>0,b[i]的值应该是b[i-1]+a[i]
int maxsum(int n, int *a)
{
int sum = 0, b = 0;
for (int i = 1; i <= n; i++)
{
if (b > 0)
b += a[i];
else b = a[i];
if (b > sum)
sum = b;
}
return sum;
}
推广到二维的最大子矩阵和问题:
int maxsum2(int m, int n, int **a)
{
int sum = 0;
int *b = new int[n + 1];
for (int i = 1; i <= m; i++)
{
for (int k = 1; k <= n; k++)
b[k] = 0; //b[k]记录第i行到第j行的第k列的数字之和
for (int j = i; j <= m; j++) {
for (int k = 1; k <= n; k++)
b[k] += a[j][k]; //i=1,j=1;i=1,j=2;...i=2,j=2;i=2,j=3;.....
int max = Maxsum(n, b); //一维数字最大字段和
if (max > sum)
sum = max;
}
}
return sum;
}