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.


Keep three pointers, one always points to current minimum number, one always points to current maximum number, one keeps on updating max result.

    int maxProduct(vector<int>& nums) {
        int pre_min = 1;
        int pre_max = 1;
        int maxRes = INT_MIN;
        for(int i = 0; i < nums.size(); ++i) {
            int cur_min = min(min(pre_min * nums[i], pre_max * nums[i]), nums[i]);
            int cur_max = max(max(pre_min * nums[i], pre_max * nums[i]), nums[i]);
            maxRes = max(maxRes, cur_max);
            
            pre_min = cur_min;
            pre_max = cur_max;
        }
        return maxRes;
    }

你可能感兴趣的:(LeetCode 152. Maximum Product Subarray)