首页 > 其他 > 详细

[LeetCode] Maximum Product Subarray

时间:2014-10-20 08:35:59      阅读:218      评论:0      收藏:0      [点我收藏+]

题目描述:

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

最大值的产生:

  1. if A[i] > 0, MaxValue = A[i] * MaxValue
  2. if A[i] < 0, MinValue = A[i] * MinValue
  3. 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 };

 

[LeetCode] Maximum Product Subarray

原文:http://www.cnblogs.com/skycore/p/4036394.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!