LeetCode-Maximum Product Subarray
來源:程序員人生 發布時間:2015-02-03 08:42:18 閱讀次數:3874次
題目鏈接:點擊打開鏈接
題目信息:
Find the contiguous subarray within an array (containing at least one number) which has the largest product.
For example, given the array [2,3,⑵,4]
,
the contiguous subarray [2,3]
has the largest product = 6
.
解題思路: 習慣最小字符串的和,突然來了1道最小字符串的乘積,也挺成心思。
分兩種情況討論:字符數組中無0,有0。兩種情況。
(1)字符數組中無0
字符數組中,其實就兩種,偶數個負數,奇數個負數。
1,偶數個負數,例如 [ ⑴ 2 3 ⑷ 5],很明顯最大的字符串就是全部。
2,奇數個負數,例如 [⑵ 2 5 ⑷ ⑶], 最大的字符串就是,第1個負數后面的子串[2 5 ⑷ ⑶].
所以綜上所述,最大字符串就只有兩種情況,1種是全部字符串,1種是第1個負數后面的字符串。所以只要存儲這兩種情況下的值, 再進行比較就可以得出最后結果。
(2)字符串中有0
前面能實現,我們就把0后的數組,當做1個新的數組就可以實現了。例如[5 6 ⑸ 0 2 3 8 9 ⑸],就能夠把0后面的數組看成新數組就行
[2 3 8 9 ⑸];
代碼:
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
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈