LeetCode-Maximum Product Subarray
來源:程序員人生 發(fā)布時(shí)間:2015-02-03 08:42:18 閱讀次數(shù):3869次
題目鏈接:點(diǎn)擊打開鏈接
題目信息:
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
.
解題思路: 習(xí)慣最小字符串的和,突然來了1道最小字符串的乘積,也挺成心思。
分兩種情況討論:字符數(shù)組中無0,有0。兩種情況。
(1)字符數(shù)組中無0
字符數(shù)組中,其實(shí)就兩種,偶數(shù)個(gè)負(fù)數(shù),奇數(shù)個(gè)負(fù)數(shù)。
1,偶數(shù)個(gè)負(fù)數(shù),例如 [ ⑴ 2 3 ⑷ 5],很明顯最大的字符串就是全部。
2,奇數(shù)個(gè)負(fù)數(shù),例如 [⑵ 2 5 ⑷ ⑶], 最大的字符串就是,第1個(gè)負(fù)數(shù)后面的子串[2 5 ⑷ ⑶].
所以綜上所述,最大字符串就只有兩種情況,1種是全部字符串,1種是第1個(gè)負(fù)數(shù)后面的字符串。所以只要存儲(chǔ)這兩種情況下的值, 再進(jìn)行比較就可以得出最后結(jié)果。
(2)字符串中有0
前面能實(shí)現(xiàn),我們就把0后的數(shù)組,當(dāng)做1個(gè)新的數(shù)組就可以實(shí)現(xiàn)了。例如[5 6 ⑸ 0 2 3 8 9 ⑸],就能夠把0后面的數(shù)組看成新數(shù)組就行
[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;
}
};
轉(zhuǎn)載請(qǐng)注明作者:vanish_dust
生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對(duì)您的學(xué)習(xí)有所幫助,可以手機(jī)掃描二維碼進(jìn)行捐贈(zèng)