Loading

【leetcode】152. Maximum Product Subarray

  Given an integer array nums, find a contiguous non-empty subarray within the array that has the largest product, and return the product. It is guaranteed that the answer will fit in a 32-bit integer.

A subarray is a contiguous subsequence of the array.

 Example 1:

Input: nums = [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.

        这道题是求一串数组中最大的连续子序列乘积的最大值,对于这类题一般都是用动态规划,这里很容易想到用一个dp[n],存储包含当前数字的子序列的最大乘积值。
       对于当前的dp[n],可以有两种情况,要么nums[n]*dp[n-1],要么就是nums[n],我一开始以为状态转移就是这样的,即dp[n]=max(nums[n]*dp[n-1],nums[n])。
  但实际上由于符号的影响,最大值和最小值会出现翻转。
  例如对于这种数组[2,-3,-4],最大值就是-4*(-6),(-6)相当于是包含-3时的子序列的最小值。
  所以可以发现,最大值都是从最大乘积、最小乘积算出来的,所以这里还要开辟一个数组,用于存储包含当前数字的子序列的最小乘积值,只有想到这里,这道题才能解答出来。

class Solution {
public:
    int maxProduct(vector<int>& nums) {
        int res = nums[0], n = nums.size();
        vector<int> dp1(n, 0), dp2(n, 0);
        dp1[0] = nums[0];
        dp2[0] = nums[0];
        for (int i = 1; i < n; ++i) {
            dp1[i] = max(max(dp1[i - 1] * nums[i], dp2[i - 1] * nums[i]), nums[i]);
            dp2[i] = min(min(dp1[i - 1] * nums[i], dp2[i - 1] * nums[i]), nums[i]);
            res = max(res, dp1[i]);
        }
        return res;
    }
};
posted @ 2021-12-05 00:15  aalanwyr  阅读(25)  评论(0编辑  收藏  举报