leetcode 152. 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 maxProduct(vector<int>& nums) {
        if(nums.size() == 1)return nums[0];
        int dpmin = nums[0];
        int dpmax = nums[0];
        int resmax= dpmax;
        for(int i = 1; i < nums.size(); i++){
            int mx = dpmax * nums[i];
            int mn = dpmin * nums[i];
            
            dpmax = max(max(mn, mx), nums[i]);
            dpmin = min(min(mn, mx), nums[i]);
            resmax = max(dpmax, resmax);
        }
        return resmax;
    }
};






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