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.
分析:
本题要求连续子数组的最大乘积。需要考虑的是数组中存在0和负数的情况。具体代码如下:
class Solution {
public:
int maxProduct(vector<int>& nums) {
int num = nums.size();
int maxPro = nums[0], minPro = nums[0], ret = nums[0];
for(int i = 1; i < num; ++i)
{
int a = maxPro*nums[i]; //若nuts[i] > 0,则a为最大值,反之a为最小值
int b = minPro*nums[i];
maxPro = max(max(a,b), nums[i]); //考虑到nuts[i]== 0的情况,需要将nuts[i]进行比较,等到i+1是更新maxPro的值
minPro = min(min(a,b), nums[i]);
ret = max(maxPro,ret);//由于可能遇到中间有0的情况,因此每次都要更新最大值
}
return ret;
}
};