您的位置:首页 > 其它

【Leet Code】152. Maximum Product Subarray---Medium

2015-11-26 15:38 525 查看
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
.
思路一:
well, we need two variables to remember the maxim positive product(posMax) ending at nums[i-1] and in fact
minimum negative product (I define it to be negMax) ending at nums[i-1]. So when we get nums[i], we just see if nums[i] is positive, negative, or zero? If it is postive, okay, the current biggest positive product posMax is the previous posMax product nums[i]
if the previous posMax is bigger than 1, else it is nums[i]; and if it is negative, something like when it is positive. Finally, if it is zero, well, both posMax and negMax is zero. Remember both posMax and negMax end at nums[i].

定义两个变量:posMax记录nums[i]前面的最大正值乘积,negMax记录nums[i]前面的负值最小乘积。
对nums[i],

如果nums[i]>0,如果posMax>1,posMax = posMax*nums[i],否则,posMax=nums[i];negMax
*= nums[i]。

如果nums[i]<0,先保存negMax的值到negTemp,如果posMax>1,negMax
= posMax*nums[i],否则,negMax=nums[i];posMax
= nums[i] * negTemp。

如果nums[i]==0,posMax
= 0, negMax=0.

代码实现一:

class Solution {
public:
int maxProduct(vector<int>& nums) {
int n = nums.size();
if(n ==0 ) return 0;
else if(n == 1) return nums[0];

int posMax, negMax, maxim;
posMax = max(0, nums[0]);
negMax = min(0, nums[0]);
maxim = posMax;

for(int i=1; i<n; i++)
{
if(nums[i] > 0)
{
posMax = max(1, posMax)*nums[i];
negMax = negMax*nums[i];
}
else if(nums[i] < 0)
{
int negTemp = negMax;
negMax = max(1, posMax)*nums[i];
posMax = negTemp*nums[i];
}
else
{
posMax = 0;
negMax = 0;
}
if(posMax > maxim)
maxim = posMax;
}

return maxim;
}
};


代码实现二:

class Solution {
public:
int maxProduct(vector<int>& nums) {
int proMin, proMax, res;
res = proMax = proMin = nums[0]; // max, min means max and min product among the subarrays whose last element is nums[i].
for (int i = 1; i < nums.size(); i++)
{
if (nums[i] > 0) {
proMax = max(proMax * nums[i], nums[i]);
proMin = min(proMin * nums[i], nums[i]);
}
else
{
int lastMax = proMax;
proMax = max(proMin * nums[i], nums[i]);
proMin = min(lastMax * nums[i], nums[i]);
}
res = max(res, proMax);
}
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: