class Solution {
public:
    int maxProduct(vector<int>& nums) {
        if(nums.empty())
            return 0;
        if(nums.size() == 1)
            return nums[0];
            
        int maxAll = nums[0];       //global maximum
        int maxLast = nums[0];      //maximum including last element
        int maxCur;                 //maximum including current element
        int minLast = nums[0];      //minimum including current element
        int minCur;                 //minimum including last element
        for(int i = 1; i < nums.size(); i ++)
        {
            maxCur = max(nums[i], max(maxLast*nums[i], minLast*nums[i]));
            minCur = min(nums[i], min(maxLast*nums[i], minLast*nums[i]));
            maxLast = maxCur;
            minLast = minCur;
            maxAll = max(maxAll, maxCur);
        }
        return maxAll;
    }
};

因为nums可能包含负数,因此之前最小的乘积*当前值,有可能成为最大值;而之前最大的乘积*当前值,有可能成为最小值。

因此,每次计算的时候,把目前的最大乘积和最小乘积都保存下来,用于下一次计算。

 

补充一个python的实现:

 1 class Solution:
 2     def maxProduct(self, nums: 'List[int]') -> 'int':
 3         n = len(nums)
 4         if n == 0:
 5             return 0
 6         elif n == 1:
 7             return nums[0]
 8         maxAll,preMax,preMin = nums[0],nums[0],nums[0]
 9         curMax,curMin = nums[0],nums[0]
10         for i in range(1,n):
11             curMax = max(nums[i],max(preMax*nums[i],preMin*nums[i]))
12             curMin = min(nums[i],min(preMax*nums[i],preMin*nums[i]))
13             preMax,preMin = curMax,curMin
14             maxAll = max(maxAll,curMax)
15         return maxAll

 

posted on 2018-10-18 19:29  Sempron2800+  阅读(133)  评论(0编辑  收藏  举报