【題解】LeetCode 152. Maximum Product Subarray

【題目敘述】https://leetcode.com/problems/maximum-product-subarray/

class Solution {
public:
    int maxProduct(vector<int>& nums) {
        int ans = nums[0], mx = 1, pre = 1;
        for (int i:nums){
            if (i == 0){
                ans = max(ans, 0);
                pre = 1;
                mx = 1;
                continue;
            }
            pre *= i;
            if (pre < 0){
                ans = max(ans, pre/mx);
                if (mx == 1) mx = pre;
                else mx = max(mx, pre);
            }
            else ans = max(ans, pre);
        }
        return ans;
    }
};
分享本文 Share with friends