連續子數組的最大和

來源:互聯網
上載者:User

標籤:動態   ret   轉換   color   sts   vector   code   連續子數組   bar   

數組

最基礎做法:

    int FindGreatestSumOfSubArray(vector<int> array) {        int len = array.size();        int dp[400][400] = {0};        int res = -214748;        for(int i = 1; i < len;i++)        {            dp[i][i] = array[i-1];            if(dp[i][i] > res)                res = dp[i][i];        }        for(int i = 1; i <= len;i++)        {            for(int j = i+1; j <= len;j++)            {                dp[i][j] = dp[i][j-1] + array[j-1];                if(dp[i][j] > res)                    res = dp[i][j];            }        }        return res;    }

動態規劃想法:

    int FindGreatestSumOfSubArray(vector<int> array) {        int len = array.size();        int dp[400] = {0};        int res = array[0];        for(int i = 1; i <= len;i++)        {            dp[i] = dp[i-1]+array[i-1] > array[i-1] ? dp[i-1]+array[i-1]:array[i-1];            if(res < dp[i])                res = dp[i];        }        return res;    }

1.dp方程:dp[i] 為以i為結尾的數組最大值。

2.轉換方程  : 我們只需要保證以i為結尾的最大值,比較第i-1個值+當前值,與當前值,選取大的。

      可以通俗的理解成,前面已經是負的了,重新設一個新的起點。

連續子數組的最大和

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.