Share my 8ms solution


  • 0
    O
    class Solution {
    public:
        int maxProduct(vector<int>& nums) {
            int n = nums.size();
            if (n <= 0) return 0;
            int max_val = nums[0], ans = nums[0];
            int min_val = nums[0];
            for (int i = 1; i < n; i++) {
                int max_tmp = max_val, min_tmp = min_val;
                max_val = nums[i];
                max_val = max(nums[i] * max_tmp, max_val);
                max_val = max(nums[i] * min_tmp, max_val);
                min_val = nums[i];
                min_val = min(nums[i] * max_tmp, min_val);
                min_val = min(nums[i] * min_tmp, min_val);
                ans = max(ans, max_val);
            }
            return ans;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.