Maximum Product Subarray - LeetCode

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.

思路:DP。这里我们实际上不需要O(n)的空间,只需要用变量将遍历到的最大值记录下来就可以。

其中,因为求的是数的乘积,有可能原本两个都是负的值相乘后会成为最大的乘积。

因此,我们需要维护两个变量,MaxPre和MinPre。

MaxPre为最后一位是当前位置前一位的区间最大乘积。

MinPre为最后一位是当前位置前一位的区间最小乘积。

之后,将当前位置考虑在内的话,有:

MaxSoFar = max(max(MaxPre * nums[i], MinPre * nums[i]), nums[i]);

MinSoFar = min(min(MinPre * nums[i], MaxPre * nums[i]), nums[i]);

然后用MaxResFound记录下迭代过程中MaxSoFar的最大值,即为结果。

 1 class Solution {
 2 public:
 3     int maxProduct(vector<int>& nums) {
 4         int n = nums.size();
 5         if (n == 0) return 0;
 6         int MaxSoFar, MinSoFar, MaxResFound, MaxPre, MinPre;
 7         MaxPre = MinPre = MaxSoFar = MinSoFar = MaxResFound = nums[0];
 8         for (int i = 1; i < n; i++)
 9         {
10             MaxSoFar = max(max(MaxPre * nums[i], MinPre * nums[i]), nums[i]);
11             MinSoFar = min(min(MinPre * nums[i], MaxPre * nums[i]), nums[i]);
12             MaxResFound = max(MaxResFound, MaxSoFar);
13             MaxPre = MaxSoFar;
14             MinPre = MinSoFar;
15         }
16         return MaxResFound;
17     }
18 };

 

posted @ 2015-11-04 09:47  fenshen371  阅读(147)  评论(0编辑  收藏  举报