數組的最大子數組積 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.

思路:在《數組的最大子數組和》問題中,有一個很好的方法,一次遍歷就能求得結果。本問題和它非常類似,一個是考察子數組的和,一個是考察子數組的積。在最大子數組和問題中,當子數組和累積爲負數的時候則需要捨去之前的部分,因爲負數可以看做是“拖累”。而在最大子數組積問題中則不是這樣,因爲負數*負數可以變回正數,因此不能因爲子數組積累計爲負數就將其捨去,一個符號的差別可以將最小轉變爲最大。因此在一次遍歷的過程中,可以同時記錄着最小和最大。

class Solution {
public:
int getmax(int a, int b, int c)
{
    int m = a>b?a:b;
    return m>c?m:c;
}
int getmin(int a, int b, int c)
{
    int m = a<b?a:b;
    return m<c?m:c;
}

int maxProduct(int A[], int n)
{
    int max, tmpmax, tmpmin;
    max = tmpmax = tmpmin = A[0];
    for(int i=1;i<n;i++)
    {
        int tmin = tmpmin; //tmin、tmin臨時用,以免兩次求最值時丟失原值。
        int tmax = tmpmax;
        tmpmin = getmin(tmax*A[i], tmin*A[i], A[i]);
        tmpmax = getmax(tmin*A[i], tmax*A[i], A[i]);
        
        if(max < tmpmax)
            max = tmpmax;
    }
    return max;
}

};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章