152. Maximum Product Subarray (最大乘积子数列)

152. Maximum Product Subarray (最大乘积子数列)

  • Maximum Product Subarray 最大乘积子数列
    • 题目链接
    • 题目描述
    • 题目分析
      • 方法动态规划
        • 算法描述
    • 参考代码

题目链接

https://leetcode.com/problems/maximum-product-subarray/description/

题目描述

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.

题目分析

这道题里需要注意负负相乘得正的问题,所以需要用二维数组来记录乘积的最大值和最小值。如果当前数字为正,那么乘正的乘积会更大;反之乘负的成绩会比较大。

方法:动态规划

算法描述

nProducts记录负乘积,用pProducts记录正乘积
遍历nums,对nums[i]
nums[i] > 0:

if (pProducts[i - 1] * nums[i] >= nums[i])
    pProducts[i] = pProducts[i - 1] * nums[i];
else
    pProducts[i] = nums[i];

if (nProducts[i - 1] * nums[i] < nums[i])
    nProducts[i] = nProducts[i - 1] * nums[i];
else
    nProducts[i] = nums[i];

nums[i] < 0:

if (nProducts[i - 1] * nums[i] >= nums[i])
    pProducts[i] = nProducts[i - 1] * nums[i];
else
    pProducts[i] = nums[i];

if (pProducts[i - 1] * nums[i] < nums[i])
    nProducts[i] = pProducts[i - 1] * nums[i];
else
    nProducts[i] = nums[i];

nums[i] == 0:

pProducts[i] = nProducts[i] = 0;

参考代码

class Solution {
public:
    int maxProduct(vector<int>& nums) {
        vector<int> pProducts(nums.size(), 1), nProducts(nums.size(), 1);
        pProducts[0] = nProducts[0] = nums[0];
        int max = pProducts[0];
        for (int i = 1; i < nums.size(); i++) {
            if (nums[i] > 0) {
                if (pProducts[i - 1] * nums[i] >= nums[i])
                    pProducts[i] = pProducts[i - 1] * nums[i];
                else
                    pProducts[i] = nums[i];

                if (nProducts[i - 1] * nums[i] < nums[i])
                    nProducts[i] = nProducts[i - 1] * nums[i];
                else
                    nProducts[i] = nums[i];
            }
            else if (nums[i] < 0) {
                if (nProducts[i - 1] * nums[i] >= nums[i])
                    pProducts[i] = nProducts[i - 1] * nums[i];
                else
                    pProducts[i] = nums[i];

                if (pProducts[i - 1] * nums[i] < nums[i])
                    nProducts[i] = pProducts[i - 1] * nums[i];
                else
                    nProducts[i] = nums[i];
            }
            else {
                pProducts[i] = nProducts[i] = 0;
            }

            if (pProducts[i] > max)
                max = pProducts[i];
        }
        return max;
    }
};

你可能感兴趣的:(LeetCode)