LeetCode 152. Maximum Product Subarray(最大连续乘积)

 
class Solution {
public:
    int maxProduct(vector<int>& nums) {
        vector<int> dpmax(nums.size());
        vector<int> dpmin(nums.size());
        dpmax[0] = nums[0];
        dpmin[0] = nums[0];
        int ans = nums[0];
        for (int i = 1; i < nums.size(); ++i)
        {
            dpmax[i] = max(dpmax[i - 1] * nums[i], nums[i]);
            dpmax[i] = max(dpmin[i - 1] * nums[i], dpmax[i]);
            
            dpmin[i] = min(dpmin[i - 1] * nums[i], nums[i]);
            dpmin[i] = min(dpmax[i - 1] * nums[i], dpmin[i]);
            ans = max(ans, dpmax[i]); 
        }
        return ans;
    }
};

维护两个数组,分别表示从0到包括第i个数字的最大值和最小值。 

点赞