您的位置:首页 > 其它

【LeetCode】152. Maximum Product Subarray

2016-03-28 14:57 344 查看

题目:

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
.

提示:

这道题可以使用动态规划求解,但是由于是乘法运算,所以情况更加复杂。联想乘法运算的性质:两个负数相乘得到一个正数,也就是说我们在计算过程中,如果产生了一个很大的负数,之后又遇到了一个负数,那么其乘积就会变成正数,进而可能成为潜在的答案。因此,我们创建两个变量,分别记录运算过程中的最大值和最小值。另外,当遇到负数时,把这两个变量进行交换(因为那个最小值乘以负数之后就会成为最大值)。具体看下列代码:

代码:

class Solution {
public:
int maxProduct(vector<int>& nums) {
if (nums.empty()) {
return 0;
}
int res = nums[0];
for (int i = 1, imax = res, imin = res; i < nums.size(); ++i) {
if (nums[i] < 0) {
swap(imax, imin);
}
// 幸运的是,这样的做法对数值0也同样有效
imax = max(nums[i], imax * nums[i]);
imin = min(nums[i], imin * nums[i]);
res = max(res, imax);
}
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: