算法一:
#include<iostream>
using namespace std;
int MaxSubseqSum1(int A[],int N);
int main()
{
int a[]={4,-3,5,-2,-1,2,6,-2};
int b;
//b=MaxSubseqSum1(a,8);
b=MaxSubseqSum1(a,sizeof(a)/sizeof(a[0]));//数组的长度。
cout<<b<<endl;
return 0;
}
int MaxSubseqSum1(int A[],int N)
{
int ThisSum,MaxSum=0;
int i,j,k;
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;
}
算法二:
#include<iostream>
using namespace std;
int MaxSubseqSum2(int A[],int N);
int main()
{
int a[]={4,-3,5,-2,-1,2,6,-2};
int b;
//b=MaxSubseqSum1(a,8);
b=MaxSubseqSum2(a,sizeof(a)/sizeof(a[0]));
cout<<b<<endl;
return 0;
}
int MaxSubseqSum2(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[j];
if(ThisSum>MaxSum)
MaxSum=ThisSum;
}
}
return MaxSum;
}
算法三:分而治之
#include<iostream>
using namespace std;
int MaxSubSum3(const int A[],int Left,int Right);
int Max3(int a,int b,int c);
int main()
{
int a[]={4,-3,5,-2,-1,2,6,-2};
int b;
//b=MaxSubseqSum1(a,8);
b=MaxSubSum3(a,0,sizeof(a)/sizeof(a[0])-1);
cout<<b<<endl;
return 0;
}
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=MaxSubSum3(A,Left,Center);
MaxRightSum=MaxSubSum3(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 MaxSubSum3(A,0,N-1);
}
int Max3(int a,int b,int c)
{
int max;
max=a;
if(a>b&&a>c)
max=a;
else if(b>c)
max=b;
else
max=c;
}
算法四:在线处理,即时处理
#include<iostream>
using namespace std;
int MaxSubseqSum4(int A[],int N);
int main()
{
int a[]={4,-3,5,-2,-1,2,6,-2};
int b;
//b=MaxSubseqSum1(a,8);
b=MaxSubseqSum4(a,sizeof(a)/sizeof(a[0]));
cout<<b<<endl;
return 0;
}
int MaxSubseqSum4(int A[],int N)
{
int ThisSum=0,MaxSum=0;
int i;
for(i=0;i<N;i++)
{
ThisSum+=A[i];
if(ThisSum>MaxSum)
MaxSum=ThisSum;
else if(ThisSum<0)
ThisSum=0;
}
return MaxSum;
}