LeetCode152. Maximum Product Subarray——动态规划

文章目录

    • 一、题目
    • 二、题解

一、题目

Given an integer array nums, find a
subarray
that has the largest product, and return the product.

The test cases are generated so that the answer will fit in a 32-bit integer.

Example 1:

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

Input: nums = [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.

Constraints:

1 <= nums.length <= 2 * 104
-10 <= nums[i] <= 10
The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.

二、题解

class Solution {
public:
    int maxProduct(vector<int>& nums) {
        int n = nums.size();
        int res = nums[0];
        for(int i = 1,minVal = nums[0],maxVal = nums[0];i < n;i++){
            int curMin = min({nums[i],minVal * nums[i],maxVal * nums[i]});
            int curMax = max({nums[i],minVal * nums[i],maxVal * nums[i]});
            minVal = curMin;
            maxVal = curMax;
            res = max(res,maxVal);
        }
        return res;
    }
};

你可能感兴趣的:(动态规划,算法,leetcode,数据结构,c++)