所谓最大子序列和问题:
给定整数A1,A2,... ,An(可能有负数),求∑Ak的最大值(k从i到j),如果所有整数均为负数,则最大子序列和为0。
下面通过4个算法来求解最大子序列和问题,每个算法的效率都不一样且效率越来越好。
算法代码来自《数据结构与算法分析——C语言描述》第2版
/******算法 1,时间复杂度O(n3) ******/
int MaxSubSequenceSum(const int A[ ],int N)
{
int ThisSum, MaxSum, i, j, k;
MaxSum = 0;
for(i = 0;i < N;i++)
for(j = i;j < N;j++)
{
ThisSum = 0;
for(k = i;k < j;k++)
ThisSum += A[k];
if(ThisSum > MaxSum)
MaxSum = ThisSum;
}
return MaxSum;
}
/******算法 2,时间复杂度O(n2) ******/
int MaxSubSequenceSum(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;
}
/******算法 3,采用分治算法,时间复杂度O(nlogn) ******/
int Max3(int x,int y,int z)
{
return (x>y)?(x>z?x:z):(y>z?y:z);
}
static int MaxSubSum(const int A[ ],int Left,int Right)
//static所修饰的函数,表示该函数只能在本文件(模块) //中使用,其他文件不能调用该函数
{
int MaxLeftSum, MaxRightSum;
int MaxLeftBorderSum, MaxRightBorderSum;
int LeftBorderSum, RightBorderSum;
int Center, i;
if(Left == Right) /*Base case*/
if(A[Left] > 0)
return A[Left];
else
return 0;
Center = (Left + Right)/2;
MaxLeftSum = MaxSubSum(A,Left,Center);
MaxRightSum = MaxSubSum(A,Center+1,Right);
MaxLeftBorderSum = 0; LeftBorderSum = 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 > MaxRightBorderSum)
MaxRightBorderSum = RightBorderSum;
}
return Max3(MaxLeftSum,MaxRightSum,MaxLeftBorderSum + MaxRightBorderSum);
}
int MaxSubSequenceSum(const int A[ ],int N)
{
return MaxSubSum(A,0,N-1);
}
/******算法4 ,时间复杂度O(n) ******/
int MaxSubSequenceSum(const int A[],int N)
{
int ThisSum, MaxSum, i;
ThisSum = MaxSum = 0;
for(i = 0;i < N;i++)
{
ThisSum += A[i];
if(ThisSum > MaxSum)
MaxSum = ThisSum;
else if(ThisSum < 0)
ThisSum = 0;
}
return MaxSum;
}