首页 > 代码库 > 求数组的子数组之和的最大值?

求数组的子数组之和的最大值?

自己写的代码考虑未周全,引入了额外的空间复杂度:

//求数组的子数组之和的最大值
#include <iostream>
#define N 12
using namespace std;
int main()
{
    //int a[]={-5,2,3,-3,-2,3,1,-5};
    //int a[]={-5,2,0,3,-2,3,4,5};
    int a[]={1,-2,3,10,-4,7,2,-5};
    int flag,max,i,j=0;
    int sum[N]={0};
    //(1)记录子数组和
    for(i=0,sum[j]=a[i];i<7;++i)
    {
        if((a[i]+a[i+1])>=a[i])
        {
            if(a[i]>=0)
                sum[j]+=a[i+1];
            else
                    sum[j]=a[i+1];
        }
        else if (a[i]<a[i+1])
            {
                //j++;
                sum[j]=a[i+1];
            }
        else
            j++;
    }
    flag=j;
    //(2)遍历子数组和,求最大值
    for(j=1,max=sum[0];j<=flag;j++)
    {
        if(sum[j]>max)
            max=sum[j];
    }
    cout<<max<<endl;
    getchar();
    return 0;
}


较为标准的参考写法:

bool g_InvalidInput = false;
int FindGreatestSumOfSubArray(int *pData,int nLength)
{
    if((pData=http://www.mamicode.com/=NULL)||(nLength<=0))
    {
        g_InvlidInput = true;
        return 0;
    }
    g_InvlidInput = false;
    int nCurSum = 0;
    int nGreatestSum = 0x80000000;
    for(int i=0;i<nLength;++i)
    {
        if(nCurSum<=0)
            nCurSum = pData[i];
        else
            nCurSum += pData[i];
        if(nCurSum>nGreatestSum)
            nGreatestSum = nCurSum;
    }
    return nGreatestSum;
}