您的位置:首页 > 其它

leetcode - Maximum Product Subarray

2014-10-26 18:59 260 查看
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
.

//这里有一点要注意,如果两个很小的负数相乘,得到的结果可能最大。所以,要记录更新的最大值max,最小值min.
class Solution {
public:
int maxProduct(int A[], int n) {
if(n < 1) return 0;
int max = A[0], min = A[0];
int res = A[0];
for (int i = 1; i < n; i++)
{
int t = A[i] * min;
min = std::min(A[i],std::min(t,max*A[i]));
max = std::max(A[i],std::max(t,max*A[i]));
res = std::max(res,max);
}
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: