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