题目描述:
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]
下面是该题代码:
1 class Solution { 2 public: 3 int maxProduct(int A[], int n) { 4 if (n == 0) {return 0;} 5 if (n == 1) {return A[0];} 6 7 int result = A[0]; 8 int CurMin = A[0]; 9 int CurMax = A[0]; 10 11 for (int i = 1; i < n; ++i) { 12 int temp = CurMin * A[i]; 13 CurMin = min(A[i], min(temp, CurMax * A[i])); 14 CurMax = max(A[i], max(temp, CurMax * A[i])); 15 result = max(result, CurMax); 16 } 17 18 return result; 19 } 20 };