首页 > 代码库 > 数组中最大子数组之和

数组中最大子数组之和

题目

[1, -2, 3, 5, -3, 2] 返回:8
[0, -2, 3, 5, -1, 2] 返回:9
[-9, -2, -3, -5, -3] 返回:-2

主要程序

int MaxSum4(int *A, int n,int &beg,int &end)
{
    if(A==NULL||n<=1)
    {
        cout<<"error input"<<‘\n‘;
        exit(0);
    }
    if(n==1)
        return A[0];
    int pos = 0;
    int CurSum = A[0];
    int MaxSum = A[0];
    for(int i = 1; i<n;++i)
    {
        if(CurSum<=0)
            CurSum = 0;
        CurSum += A[i];
        if(CurSum>=MaxSum)
        {
            MaxSum = CurSum;
            pos = i;
        }
    }
    int pos1 = 0,max1 = A[0];
    CurSum = A[0]; 
    for(int i = 1;i<=n-1;++i)
    {
        CurSum += A[i];
        if(CurSum>=max1)
        {
            max1 = CurSum;
            pos1 = i;
        }
    }
    CurSum = A[n-1];
    int pos2 = n-1, max2 = A[n-1];
    for(int j = n-2; j>=0; --j)
    {
        CurSum += A[j];
        if(CurSum>=max2)
        {
            max2 = CurSum;
            pos2 = j;
        }
    }
    int sum = 0;
    if(pos1>=pos2)
    {
        for(int i = 0; i<n; ++i)
            sum+=A[i];
    }
    else
    {
        for(int i = 0; i<=pos1; ++i)
        {
            sum+=A[i];
        }
        for(int j = n-1; j>=pos2; --j)
        {
            sum+=A[j];
        }
    }
    int temp = MaxSum>sum?MaxSum:sum;
    if(MaxSum==temp)
    {
        end = pos;
        while(temp!=0)
        {
            temp-=A[pos--];
        }
        beg = ++pos;
        return MaxSum;
    }
    else
    {
        if(pos1>=pos2)
        {
            beg = 0;
            end = n-1;
        }
        else
        {
            end = pos2;
            beg = pos1;
        }
        return sum;
    }
    return MaxSum>sum?MaxSum:sum;
}

数组中最大子数组之和