描述
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.
分析
求所有连续子序列的最大乘积。
这道题可以用动态规划的方法来求解,我们假设
f(k)
表示以
a[k]
结尾的最大乘积,
g(k)
表示以
a[k]
结尾的最小乘积,那么
f(k)=max(f(k−1)∗a[k],g(k−1)∗a[k],a[k])
g(k)=min(f(k−1)∗a[k],g(k−1)∗a[k],a[k])
那么我们要求的结果就是 max(f(0),f(1),...,f(n−1)) 。
充分理解这一点后,我们便很容易写出代码,时间复杂度 O(n) ,空间复杂度 O(1) 。
代码
class Solution {
public:
int maxProduct(vector<int>& nums) {
if (nums.size() == 1) return nums[0];
int mx = nums[0], mn = nums[0], res = nums[0];
for (int i = 1; i < nums.size(); i++) {
int tmax = mx, tmin = mn;
mx = max(max(tmax * nums[i], tmin * nums[i]), nums[i]);
mn = min(min(tmax * nums[i], tmin * nums[i]), nums[i]);
res = max(res, mx);
}
return res;
}
};