码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Maximum Product Subarray

时间:2014-10-20 08:38:54      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   ar   for   strong   sp   

题目描述:

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

标签:style   blog   http   color   io   ar   for   strong   sp   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!