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;
}
};