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
.
Difficulty:Medium
简单的注意下负号的问题,从前向后扫就行了。
int maxProduct(vector<int>& nums) {
int len = nums.size();
if(len==0) return 0;
if(len==1) return nums[0];
int ans = nums[0], temp1 = nums[0], temp2 = nums[0],Max = nums[0], Min = nums[0];
for(int i = 1;i<len;i++)
{
temp1 = Max*nums[i];
temp2 = Min*nums[i];
Max = max(max(temp1,temp2),nums[i]);
Min = min(min(temp1,temp2),nums[i]);
ans = max(Max,ans);
}
return ans;
}
};