2.14 求數組的子數組之和的最大值,2.14數組

來源:互聯網
上載者:User

2.14 求數組的子數組之和的最大值,2.14數組
題目:給定一個一維數組,求這個數組的子數組之和的最大值。


最佳方法:動態規劃!


一、
可以將一個大問題(N個元素數組)轉化為一個較小的問題(N-1個元素數組)。。
假設已經知道(A[1],...A[n-1])中最大的子數組的和為:All[1]
並且已經知道(A[1],...A[n-1])中包括A[1]的子數組的最大和為start[1]


所以最終的解All[0] = max(A[0], A[0]+start[1], All[1])
所以通過DP來求解!


代碼如下:

#include <iostream>#define MAXN 10000using namespace std;int A[MAXN], n, start[MAXN], All[MAXN];int max(int x, int y) {return x > y ? x : y;}int MaxSum(int *A, int n) {start[n - 1] = A[n - 1];All[n - 1] = A[n - 1];for(int i = n-2; i >= 0; --i) {start[i] = max(A[i], start[i + 1] + A[i]);All[i] = max(All[i + 1], start[i]);}return All[0];}int main() {cin >> n;for(int i = 0; i < n; ++i) cin >> A[i];cout << MaxSum(A, n) << endl;return 0;}



二、
上面那種方法時間複雜度為:O(N),但是空間複雜度不熱觀。
所以下面尋求空間複雜度為O(1)的演算法。


思路:由上面那兩個遞推式
start[i] = max(A[i], start[i + 1] + A[i]);
All[i] = max(All[i + 1], start[i]);
      可以知道:(1)如果start[i + 1] < 0,那麼start[i] = A[i]
(2)start[i + 1]只有在計算start[i]的時候才能用到。
        All[i + 1]只有在計算All[i]的時候才能用到。


所以可以有一種時間複雜度是O(N),而空間複雜度是O(1)的演算法。


代碼:

#include <iostream>#define MAXN 10000using namespace std;int A[MAXN], n, start[MAXN], All[MAXN];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 main() {cin >> n;for(int i = 0; i < n; ++i) cin >> A[i];cout << MaxSum(A, n) << endl;return 0;}



三、
當然還有最後一種最簡單的寫法:

代碼:

#include <iostream>#define MAXN 10000using namespace std;int A[MAXN], n, start[MAXN], All[MAXN];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) {if(nStart < 0) nStart = 0;nStart += A[i];if(nStart > nAll) nAll = nStart;}return nAll;}int main() {cin >> n;for(int i = 0; i < n; ++i) cin >> A[i];cout << MaxSum(A, n) << endl;return 0;}









聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.