问题描述
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.
解释: 找出一个数组中乘积最大的子数组,返回子数组的乘积。
案例:
Input: nums = [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
解释: 上述给定数组中,最大乘积子数组是6.
基本思想
这是一个典型的两个动态数组相互更新的案例。
设定两个数组 \(dpMax\),\(dpMin\), 其中
- \(dpMax[i]\) 表示以\(nums[i]\)为结尾的子数组的最大乘积;
- \(dpMin[i]\) 表示以\(nums[i]\)为结尾的子数组的最小乘积;
则 相应更新公式如下: - \(dpMax[i]\) = max( \(dpMax[i]\)*\(nums[i-1]\) , \(dpMin[i]\) * \(nums[i-1]\), \(nums[i-1]\))
- \(dpMin[i]\) = min( \(dpMin[i]\)*\(nums[i-1]\) , \(dpMin[i]\) * \(nums[i-1]\), \(nums[i-1]\))
时间复杂度\(O(n))\)
代码
c++
int maxProduct(vector<int>& nums) {
int n = nums.size();
if (n<=1) return nums[0];
vector<int> dpMax(n,0);// 记录以nums[i]为结尾的最大子数组乘积
vector<int> dpMin(n,0);// 记录以nums[i]为结尾的最小子数组乘积
dpMax[0] = nums[0];
dpMin[0] = nums[0];
int res = nums[0];
for(int i=1;i<n;++i) {
dpMax[i] = max(max(dpMax[i-1] * nums[i], dpMin[i-1] * nums[i]), nums[i]);
dpMin[i] = min(min(dpMax[i-1] * nums[i], dpMin[i-1] * nums[i]), nums[i]);
res = max(res, dpMax[i]);
}
return res;
}
python
def maxProduct(self, nums: List[int]) -> int:
n = len(nums)
if n <=0: return 0
if n<=1 : return nums[0]
dpMax = [0] * n
dpMin = [0] * n
dpMax[0] = nums[0]
dpMin[0] = nums[0]
res = nums[0]
for i in range(1, n):
dpMax[i] = max(max(dpMax[i-1] * nums[i], dpMin[i-1] * nums[i]), nums[i])
dpMin[i] = min(min(dpMax[i-1] * nums[i], dpMin[i-1] * nums[i]), nums[i])
res = max(dpMax[i], res)
return res
标签:152,乘积,nums,int,dpMax,dpMin,Maximum,Produce,数组
From: https://www.cnblogs.com/douniwanli/p/18200847