LeetCode 53/152 Maximum Subarray/Maximum Product Subarray---DP **

來源:互聯網
上載者:User

一:Maximum Subarray

題目:

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. 連結:https://leetcode.com/problems/maximum-subarray/

分析:這題就是求最大連續字串的和,或者說是求和最大的連續子數組

此題最簡單的是暴力,但是暴力為O(N^2), 逾時。另外可以採用動態規劃來求解,關鍵是如何轉換為動態規劃問題,即如何表述成動態規劃問題。

我們用local[i]來表示以A[i]結尾的連續子數組的最大和,那麼local[0] = A[0],,  local[1]等於要麼local[0]+A[1]  要麼就等於A[1]本身,關鍵看兩者誰更大,於是便得到遞迴式local[i+1] = max(local[i]+A[i], A[i]),,,,local數組中的最大值即為所求。 迭代的過程中無需數組 因此時間複雜度為O(N), 空間複雜度為O(1).

class Solution {public:    int maxSubArray(int A[], int n) {        if(n == 0) return 0;        int sum = A[0];         // 以A[0]結束的連續子數組和最大值        int maxResult = A[0];        for(int i = 1; i < n; i++){            sum = max(A[i],A[i]+sum);      // 以A[i]結束的連續子數組和最大值            if(maxResult < sum) maxResult = sum;         }        return maxResult;    }};

二:Maximum Product Subarray

題目:

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

For example, given the array [2,3,-2,4],
the contiguous subarray [2,3] has the largest product = 6.

連結:https://leetcode.com/problems/maximum-product-subarray/

分析:此題我們不僅要儲存一個最大值,還得儲存一個最小值,因為負負相乘等於正數,比如-2 4 -5,即localMIn[i]表示以i結尾的連續字串乘積的最小值,而localMax[i]表示以i結尾的連續字串乘積的最大值,那麼localMax[i] = max(max(localMin[i]*A[i], A[i]*localMax[i]), A[i]); 而localMin[i]=min(min(localMin[i]*A[i], A[i]*localMax[i]), A[i]);

class Solution {public:    int maxProduct(int A[], int n) {        if(n == 0) return 0;        int result = A[0];        int minProduct = A[0];        int maxProduct = A[0];        for(int i = 1; i < n; i++){            int temp = max(A[i]*maxProduct, A[i]*minProduct);            temp = max(temp, A[i]);            minProduct = min(A[i]*maxProduct, A[i]*minProduct);            minProduct = min(minProduct, A[i]);            maxProduct = temp;            result = max(maxProduct, result);        }        return result;            }};


聯繫我們

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