最大数组连续子向量的最大和

最近研究最大数组,稍微总结一下,以后继续补充:

    标题:

    Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

    For example, given the array [−2,1,−3,4,−1,2,1,−5,4],
the contiguous subarray [4,−1,2,1] has the largest sum = 6.

    分析:利用扫描算法,从数组最左端开始扫描,一直到最右端,并记下所碰到的最大总和子向量。最大总和的初值为0.

    对于前m个元素,最大总和子数组要么在前m-1个元素中,要么是其结束位置为m。

    每日一道理
春蚕死去了,但留下了华贵丝绸;蝴蝶死去了,但留下了漂亮的衣裳;画眉飞去了,但留下了美妙的歌声;花朵凋谢了,但留下了缕缕幽香;蜡烛燃尽了,但留下一片光明;雷雨过去了,但留下了七彩霓虹。

    还需注意的一种情况是若所有的元素都为负值,则问题转化为求数组中的最大数。

    代码如下:

    int max(int l,int r)

    {

        return (l>r)?l:r;

    }

    int maxSubArray(int A[], int n)

    {

        int TempMax=0,Maxending=0,negative=A[0];

        for(int i=0;i<n;i++)

        {

            Maxending = max(Maxending+A[i],0);

            TempMax = max(TempMax,Maxending);

            if(A[i]>negative)negative=A[i];

        }

        if(negative<0)return negative;

        else return TempMax;

    }

文章结束给大家分享下程序员的一些笑话语录: 联想——对内高价,补贴对外倾销的伟大“民族”企业。

原文地址:https://www.cnblogs.com/xinyuyuanm/p/3076675.html