您的位置:首页 > 其它

[leetcode 152] Maximum Product Subarray

2015-01-01 18:34 387 查看
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
.

class Solution {
public:
int maxProduct(int A[], int n) {
if (n < 2) {
return A[0];
}
int min_pro = A[0];
int max_pro = A[0];
int res = A[0];
for (int i = 1; i < n; i++) {
int tmp = min_pro;
min_pro = min(min(A[i], A[i]*min_pro), max_pro*A[i]);
max_pro = max(max(A[i], A[i]*max_pro), tmp*A[i]);
res = max(res, max_pro);
}
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: