编程之美8:求数组的子数组之和的最大值

1:
int MaxSum(int *A, int n)
{
    int maximum = -INF;
    int sum;
    for (int i = 0; i < n; i++)
    {
        sum = 0;
        for (int j = i; j < n; j++)
        {
            sum += A[j];
            if (sum > maximum)
            {
                maximum = sum;
            }
        }
    }
    return maximum;
}

2:max{A[0],A[0]+Start[1],All[1]},其中All[1]为(A[1],…,A[n-1])中最大一段数组之和。
int max(int x, int y)
{
    return (x > y) ? x : y;
}

int MaxSum(int *A, int n)
{
    int nStart = A[n - 1];
    int nAll = A[n - 1];
    for (int i = n - 2; i >= 0; i--)
    {
        nStart = max(A[i], nStart + A[i]);
        nAll = max(nStart, nAll);
    }
    return nAll;
}

换一个写法:
int MaxSum(int *A, int n)
{
    int nStart = A[n - 1];
    int nAll = A[n - 1];
    for (int i = n - 2; i >= 0; i--)
    {
        if (nStart < 0)
        {
            nStart = 0;
        }
        nStart += A[i];
        if (nStart > nAll)
        {
            nAll = nStart;
        }
    }
    return nAll;
}

 

3:动态规划
currSum(j) = max{0, currSum[j-1]} + a[j]

int MaxSubArray(int *a, int n)
{
    int currSum = 0;
    int maxSum = a[0]; // 数组元素全为负的情况,返回最大值
    for (int j = 0; j < n; j++)
    {
        if (currSum >= 0)
        {
            currSum += a[j];
        }
        else
        {
            currSum = a[j];
        }
        if (currSum > maxSum)
        {
            maxSum = currSum;
        }
    }
    return maxSum;
}

原创:https://blog.csdn.net/ndzjx/article/details/84404589

    原文作者:勇二郎
    原文地址: https://blog.csdn.net/ndzjx/article/details/84404589
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞