给定包含N个数的数列,求最大的子列和(子列必须是连续的嗷)
下面给出4种算法:
#include <iostream>
using namespace std;
int maxSubseqSum1(int A[], int N);
int maxSubseqSum2(int A[], int N);
int maxSubseqSum3(int A[], int N);
int main()
{
int A[] = { 1, 3, -5, 3, 12, -5, -9, 23, 1, -5 };
int m1,m2,m3;
m1=maxSubseqSum1(A, 10);
cout << m1 << endl;
m2 = maxSubseqSum2(A, 10);
cout << m2<<endl;
m3 = maxSubseqSum3(A, 10);
cout << m3 << endl;
return 0;
}
int maxSubseqSum1(int A[], int N)
{
int maxSum = 0, thisSum = 0;
int i, j, k;
for (i = 0; i < N; i++)//这个循环用来将i遍历整个数组
{
for (j = i; j < N; j++)//这个循环用来获得由i开始的连续数列最大和
{
thisSum = 0;
for (k = i; k <= j; k++)
thisSum += A[k];//thisSum用来保存从A[i]开始到A[j]的和
if (thisSum>maxSum)//比较thissum与maxsum的值大小,从而获得连续的最大值
maxSum = thisSum;
}
}
return maxSum;
}
int maxSubseqSum2(int A[], int N)
{
int maxSum = 0, thisSum = 0;
int i, j;
for (i = 0; i < N; i++)//这个循环用来将i遍历整个数组
{
thisSum = 0;
for (j = i; j < N; j++)//这个循环用来获得由i开始的连续数列最大和
{
thisSum += A[j];
if (thisSum>maxSum)
maxSum = thisSum;
}
}
return maxSum;
}
int maxSubseqSum3(int A[], int N)//在线处理
{
int maxSum = 0, thisSum = 0;
int i;
for (i = 0; i < N; i++)//这个循环用来将i遍历整个数组
{
thisSum += A[i];
if (thisSum>maxSum)//发现更大和,更新整个结果
maxSum = thisSum;
else if (thisSum < 0)//如果thissum=0,则其不可能使后面的值变大,因此将前面的和抛弃,从头来过
thisSum = 0;
}
return maxSum;
}
其时间复杂度分别是T(N)=O(N3),T(N)=O(N2),T(N)=O(N)。下面还有一个分而治之的算法,其时间复杂度为T(N)=O(NlogN)
int Max3( int A, int B, int C )
{ /* 返回3个整数中的最大值 */
return A > B ? A > C ? A : C : B > C ? B : C;
}
int DivideAndConquer( int List[], int left, int right )
{ /* 分治法求List[left]到List[right]的最大子列和 */
int MaxLeftSum, MaxRightSum; /* 存放左右子问题的解 */
int MaxLeftBorderSum, MaxRightBorderSum; /*存放跨分界线的结果*/
int LeftBorderSum, RightBorderSum;
int center, i;
if( left == right ) { /* 递归的终止条件,子列只有1个数字 */
if( List[left] > 0 ) return List[left];
else return 0;
}
/* 下面是"分"的过程 */
center = ( left + right ) / 2; /* 找到中分点 */
/* 递归求得两边子列的最大和 */
MaxLeftSum = DivideAndConquer( List, left, center );
MaxRightSum = DivideAndConquer( List, center+1, right );
/* 下面求跨分界线的最大子列和 */
MaxLeftBorderSum = 0; LeftBorderSum = 0;
for( i=center; i>=left; i-- ) { /* 从中线向左扫描 */
LeftBorderSum += List[i];
if( LeftBorderSum > MaxLeftBorderSum )
MaxLeftBorderSum = LeftBorderSum;
} /* 左边扫描结束 */
MaxRightBorderSum = 0; RightBorderSum = 0;
for( i=center+1; i<=right; i++ ) { /* 从中线向右扫描 */
RightBorderSum += List[i];
if( RightBorderSum > MaxRightBorderSum )
MaxRightBorderSum = RightBorderSum;
} /* 右边扫描结束 */
/* 下面返回"治"的结果 */
return Max3( MaxLeftSum, MaxRightSum, MaxLeftBorderSum + MaxRightBorderSum );
}
int MaxSubseqSum3( int List[], int N )
{ /* 保持与前2种算法相同的函数接口 */
return DivideAndConquer( List, 0, N-1 );
}