标签:include oid 子序列 order seq pre -- stat lan
//MaxSubSequenceSum.cpp
#include<stdio.h>
//穷举式的尝试所有可能
int MaxSubsequenceSum1( 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;
}
//穷举法在计算i到j的和时,i到j-1的和在前一次的循环中已经计算过,故第三层for循环可以去掉
int MaxSubsequenceSum2(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;
}
//divide-and-conquer
int Max2( int A, int B)
{
if(A>B)
return A;
else
{
return B;
}
}
int Max3( int A, int B, int C)
{
return Max2(Max2(A,B),C);
}
static int MaxSubsequenceSum3(const int A[], int Left, int Right)
{
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 = MaxSubsequenceSum3(A, Left, Center);
MaxRightSum = MaxSubsequenceSum3(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);
}
//on-line algorithm
int MaxSubsequenceSum4(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;
}
int main(void)
{
int A[8] = {4,-3,5,-2,-1,2,6,-2};
int Max1 = MaxSubsequenceSum1(A,8);
int Max2 = MaxSubsequenceSum2(A,8);
int Max3 = MaxSubsequenceSum3(A,0,7);
int Max4 = MaxSubsequenceSum4(A,8);
printf("%d,%d,%d,%d\n",Max1,Max2,Max3,Max4);
return 0;
}
11,11,11,11
标签:include oid 子序列 order seq pre -- stat lan
原文地址:https://www.cnblogs.com/xiaoheng2020/p/12812352.html