首页 > 代码库 > 152. Maximum Product Subarray

152. Maximum Product Subarray

Problem statement:

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.

Solution:

It is similar with 53. Maximum Subarray. We should keep one more minimum product since the product of two negative number is a position number. The current max and min value should choose from three candidates, nums[i], cur_max * nums[i] and cur_min * nums[i].

Time complexity is O(n).

class Solution {public:    int maxProduct(vector<int>& nums) {        if(nums.empty()){            return 0;        }        int cur_max = 0;        int cur_min = 0;        int pre_max = nums[0];        int pre_min = nums[0];        int tot_max = nums[0];        for(int i = 1; i < nums.size(); i++){            cur_max = max(nums[i], max(pre_max * nums[i], pre_min * nums[i]));            cur_min = min(nums[i], min(pre_max * nums[i], pre_min * nums[i]));            pre_max = cur_max;            pre_min = cur_min;            tot_max = max(tot_max, cur_max);        }        return tot_max;    }};

 

152. Maximum Product Subarray