法1:暴力求解
int MaxSum1( int a[], int n)
{
int thisSum,maxSum = 0;
int i,j;
for ( i = 0; i < n; i++)
{
thisSum = 0;
for ( j = i; j < n ;j++)
{
thisSum += a[i];
if ( thisSum > maxSum)
maxSum = thisSum;
}
}
return maxSum;
}
法2: 在线求解
int MaxSum2 ( int a[],int n)
{
int thisSum,maxSum;
thisSum = maxSum = 0;
for ( int i = 0;i< n;i++)
{
thisSum += a[i];
if ( thisSum > maxSum )
maxSum = thisSum;
else if ( thisSum < 0 ) //当发现当前子列子和为负时,则不可能使后面子列子和增大
thisSum = 0; //就抛弃它
}
return maxSum;
}