您的位置:首页 > 其它

[LeetCode] Maximum Product Subarray

2014-10-20 08:31 295 查看
题目描述:

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
.

解题方案:

转载地址:http://blog.csdn.net/sbitswc/article/details/39546719

最大值的产生:

if A[i] > 0, MaxValue = A[i] * MaxValue

if A[i] < 0, MinValue = A[i] * MinValue

A[i]

下面是该题代码:

class Solution {
public:
int maxProduct(int A[], int n) {
if (n == 0) {return 0;}
if (n == 1) {return A[0];}

int result = A[0];
int CurMin = A[0];
int CurMax = A[0];

for (int i = 1; i < n; ++i) {
int temp = CurMin * A[i];
CurMin = min(A[i], min(temp, CurMax * A[i]));
CurMax = max(A[i], max(temp, CurMax * A[i]));
result = max(result, CurMax);
}

return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: