假如对于子段:9 2 -16 2

temp[i]表示以ai结尾的子段中的最大子段和。

在已知temp[i]的情况下,求temp [i+1]的方法是:

如果temp[i]>0 temp [i+1]= temp[i]+ai(继续在前一个子段上加上ai),

否则temp[i+1]=ai(不加上前面的子段),也就是说

状态转移方程:

temp[i] = (temp[i-1]>0?temp[i-1]:0)+buf[i];

int getMax(int buf[100],int n)

{

int temp[101],max=n*(-127);

memset(temp,0,4*(n+1));

for(int i=1;i<=n;i++)

{

temp[i] = (temp[i-1]>0?temp[i-1]:0)+buf[i];

if(max<temp[i])

max=temp[i];

}

return max;

}