给定整数a1,a2,a3,a4,...,an,求子数列和的最大值(若所有整数均为负数,则规定子序列和为0)
最直接最低效率的算法1
int
MaxSubsquenceSum1(const int A[],int N)
{
int ThisSum,MaxSum,i,j,k;
MaxSum=0;
for(i=0;i<N;i++)
{
for(j=ilj<N;j++)
{
ThisSum=0;
for(k=i;k<=j;k++)
{
ThisSum+=A[k];
}
if(ThisSum>MaxSum) MaxSum=ThisSum;
}
}
return MaxSum;
} /*O(N3)*/
算法1的稍许改进
int
MaxSubsquenceSum2(const int A[],int N)
{
int ThisSum,MaxSum,i,j;
MaxSum=0;
for(i=0;i<n;i++)
{
ThisSum=0;
for(j=i;j<N;j++)
{
ThisSum+=A[j];
if(ThisSum>MaxSum) MaxSum=ThisSum;
}
}
return MaxSum;
} /*O(N2)*/
采用分治(divide-and-conquter)策略并递归的算法3
static int
MaxSubSum3(const int A[],int Left,int Right)
{
int MaxLeftSum,MaxRightSum;
int MaxLeftBorderSum,MaxRightBorderSum;
int LeftBorderSum,RightBorderSum;
int Center,i;
if(Left==Right)
{
if(A[Left]>0) return A[Left];
else return 0;
}
Center=(Left+Right)/2;
MaxLeftSum=MaxSubsSum3(A,Left,Center);
MaxRightSum=MaxSubsSum3(A,Center+1,Right);
MaxLeftBorderSum=0;
LeftBorder=0;
for(i=Center;i>=Left;i--)
{
LeftBorderSum+=A[i];
if(LeftBorderSum>MaxLeftBorderSum)
MaxLeftBorderSum=LeftBorderSum;
}
MaxRightBorderSum=0;RightBorderSum=0;
for(i=Center+1;i<=Right;i++)
{
RightBorderSum+=A[i];
if(RightBorderSum>MaxRightSum)
MaxRightBorderSum=RightBorderSum;
}
return Max3(MaxLeftSum,MaxRightSum,MaxLeftBorder+MaxRightBorderSum); /*Max3为返回三个数中的最大数的伪函数*/
int
MaxSubsequenceSum3(const int A[],int n)
{
return MaxSubSum3(A,0,N-1);
} /*O(NlogN)*/
一个几乎完美的解法4
int
MaxSubsequenceSum(const int A[],int N)
{
int ThisSum,MaxSum,j;
ThisSum=MaxSum=0;
for(j=0;j<N;j++)
{
ThisSum+=A[j];
if(ThisSum>MaxSum)
MaxSum=ThisSum;
else if(ThisSum<0)
ThisSum=0;
}
return MaxSum;
} /*O(N)*/