[LeetCode-Dynamic Programming] Maximum product subarray

Title description

Give you an integer array nums, please find the continuous sub-array with the largest product in the array (the sub-array contains at least one number).
Examples:

输入: [2,3,-2,4]
输出: 6
解释: 子数组 [2,3] 有最大乘积 6。

输入: [-2,0,-1]
输出: 0
解释: 结果不能为 2, 因为 [-2,-1] 不是子数组。

Ideas

Because it is a product, and there are both positive and negative numbers in the array, there will be cases where the maximum value is multiplied by a negative number to become a minimum value and the minimum value is multiplied by a negative number to become a maximum value, so we need to maintain two dp arrays: dpMax and dpMin dpMax [i] is the largest sequence product ending in i, and dpMin [i] is the smallest sequence product ending in i. There are two situations:

  • When nums [i]> = 0:
    • dpMax[i] = max(dpMax[i-1]*nums[i], nums[i]);
    • dpMin[i] = min(dpMin[i-1]*nums[i], nums[i]);
  • When nums [i] <0:
    • dpMax[i] = max(dpMin[i-1]*nums[i], nums[i]);
    • dpMin[i] = min(dpMax[i-1]*nums[i], nums[i]);

In summary, there are:

  • dpMax[i] = max(dpMax[i-1]*nums[i], nums[i], dpMin[i-1]*nums[i]);
  • dpMin[i] = min(dpMin[i-1]*nums[i], nums[i], dpMax[i-1]*nums[i]);

The corresponding code is as follows:

class Solution {
public:
    int maxProduct(vector<int>& nums) {
        if(nums.empty()) return 0;

        int dpMax[nums.size()], dpMin[nums.size()];
        memset(dpMax, 0, sizeof(dpMax));
        memset(dpMin, 0, sizeof(dpMin));
        int maxPro = nums[0];
        dpMax[0] = nums[0];
        dpMin[0] = nums[0];
        for(int i=1; i<nums.size(); i++){
            dpMax[i] = max(max(dpMax[i-1]*nums[i], nums[i]), dpMin[i-1]*nums[i]);
            dpMin[i] = min(min(dpMax[i-1]*nums[i], nums[i]), dpMin[i-1]*nums[i]);
            maxPro = max(dpMax[i], maxPro);
        }
        return maxPro;
    }
};
  • Time complexity: O (n)
  • Space complexity: O (n)

Space complexity optimization:
You can use dp arrays instead of two variables. code show as below:

class Solution {
public:
    int maxProduct(vector<int>& nums) {
        if(nums.empty()) return 0;

        int curMax = nums[0];
        int curMin = nums[0];
        int maxPro = nums[0];
        for(int i=1; i<nums.size(); i++){
            int temp = curMax;    // 因为curMax在下一行可能会被更新,所以保存下来
            curMax = max(max(curMax*nums[i], nums[i]), curMin*nums[i]);
            curMin = min(min(curMin*nums[i], nums[i]), temp*nums[i]);
            maxPro = max(curMax, maxPro);
        }
        return maxPro;
    }
};
  • Time complexity: O (n)
  • Space complexity: O (1)

Guess you like

Origin www.cnblogs.com/flix/p/12739233.html