[算法]最大子段和

给定一个数组a,长度为n,数组元素为int型,求连续子段的最大和。

例如

2,2,-3,4,5,6,-8,-9的最大子段和为16,即2+2-3+4+5+6=16

int maxSubSum(int* a,int n,int& begin,int& last)
{
    int maxSum, tempSum, tBegin, tLast, i;
    i = 0;
    while(a[i] <= 0)
    {
        ++i;
    }
    tempSum = maxSum = a[i];
    tBegin = begin = i;
    tLast = last = i;
    ++i;
    while(i < n)
    {
        if(a[i] > 0)
        {
            tempSum += a[i];
            tLast = i;
            if(tempSum > maxSum)
            {
                last = tLast;
                begin = tBegin;
                maxSum = tempSum;
            }
            ++i;
        }
        else if(tempSum+a[i] > 0)
        {
            tempSum += a[i];
            tLast = i;
            ++i;
        }
        else
        {
            ++i;
            while(a[i] <= 0&& i < n)
            {
                ++i;
            }
            tBegin = i;
            tLast = i;
            tempSum = a[i];
            if(tempSum > maxSum)
            {
                last = tLast;
                begin = tBegin;
                maxSum = tempSum;
            }
        }
    }
    if(maxSum<0)
    {
        maxSum = 0;
    } 
    return maxSum;
    
}

 

你可能感兴趣的:(算法)