一、题目
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:文章来源:https://www.toymoban.com/news/detail-826212.html
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.文章来源地址https://www.toymoban.com/news/detail-826212.html
二、题解
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;
}
};
到了这里,关于LeetCode152. Maximum Product Subarray——动态规划的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!