【LeetCode】152. Maximum Product Subarray

題目:

Find the contiguous subarray within an array (containing at least one number) which has the largest product.post

For example, given the array [2,3,-2,4],spa

the contiguous subarray [2,3] has the largest product = 6.code

提示:

這道題能夠使用動態規劃求解,可是因爲是乘法運算,因此狀況更加複雜。聯想乘法運算的性質:兩個負數相乘獲得一個正數,也就是說咱們在計算過程當中,若是產生了一個很大的負數,以後又遇到了一個負數,那麼其乘積就會變成正數,進而可能成爲潛在的答案。所以,咱們建立兩個變量,分別記錄運算過程當中的最大值和最小值。另外,當遇到負數時,把這兩個變量進行交換(由於那個最小值乘以負數以後就會成爲最大值)。具體看下列代碼:blog

代碼:

class Solution {
public:
    int maxProduct(vector<int>& nums) {
        if (nums.empty()) {
            return 0;
        }
        int res = nums[0];
        for (int i = 1, imax = res, imin = res; i < nums.size(); ++i) {
            if (nums[i] < 0) {
                swap(imax, imin);
            }
            // 幸運的是,這樣的作法對數值0也一樣有效
            imax = max(nums[i], imax * nums[i]);
            imin = min(nums[i], imin * nums[i]);
            res = max(res, imax);
        }
        return res;
    }
};
相關文章
相關標籤/搜索