LeetCode-Maximum Product Subarray,maximumsubarray

來源:互聯網
上載者:User

LeetCode-Maximum Product Subarray,maximumsubarray

題目連結:點擊開啟連結

題目資訊:

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.

解題思路: 習慣最小字串的和,突然來了一道最小字串的乘積,也挺有意思。

                  分兩種情況討論:字元數組中無0,有0。兩種情況。

                 (1)字元數組中無0

                        字元數組中,其實就兩種,偶數個負數,奇數個負數。

                       1,偶數個負數,例如 [ -1 2 3 -4 5],很明顯最大的字串就是全部。

                       2,奇數個負數,例如 [-2 2 5 -4 -3], 最大的字串就是,第一個負數後面的子串[2 5 -4 -3].

                       所以綜上所述,最大字串就只有兩種情況,一種是全部字串,一種是第一個負數後面的字串。所以只要儲存這兩種情況下的值,                        再進行比較就能得出最後結果。

                   (2)字串中有0

                        前面能實現,我們就把0後的數組,當成一個新的數組就能實現了。例如[5 6 -5 0 2 3 8 9 -5],就可以把0後面的數組看成新數組就行

                       [2 3 8 9 -5];

代碼:

class Solution {public:    int maxProduct(int A[], int n) {    int preNum1 = 1;      //Remember all the Numbers    int preNum2 = 1;      //Remember all the Behind Numbers of first negative    bool start2;    int answers ;    if(n ==  0)  return 0;    if(n > 0) answers = A[0];    int negSum = 0;    for(size_t i = 0; i != n;i++) {      preNum1 *= A[i];      //cout<<"preNum1="<<preNum1<<endl;      answers = (preNum1 > answers? preNum1:answers);      if(start2 == true) {        preNum2 *= A[i];        //cout<<"preNum2="<<preNum2<<endl;        answers = (preNum2 > answers? preNum2:answers);      }      if(A[i] < 0) {        negSum ++;      }      if(negSum == 1 && start2 == false) {        start2 = true;        preNum2 = 1;       }       if(A[i] == 0) {        answers = (answers > 0) ? answers : 0;        preNum1 = 1;        preNum2 = 1;        negSum = 0;        start2 = false;       }    }    return answers;    }};
轉載請註明作者:vanish_dust

聯繫我們

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