最大子序列和

Posted xiaoheng2020

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了最大子序列和相关的知识,希望对你有一定的参考价值。

//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
",Max1,Max2,Max3,Max4);

    return 0;
}

运行结果

11,11,11,11

以上是关于最大子序列和的主要内容,如果未能解决你的问题,请参考以下文章

子序列最大和

最大连续子序列问题(tyvj1305)

求连续序列的最大子序列和

dp-最大连续子序列的和

题目1077:最大序列和(最大连续子序列和)

算法小总结最大连续子序列和最大连续子矩阵的关系与实现