628. Maximum Product of Three Numbers

Given an integer array, find three numbers whose product is maximum and output the maximum product.

给一个数组,找出三个数,使得他们的乘积最大。

分类讨论 max1 max2 max3 min1 min2

1.max有3个正数 ans = max1*max2*max3

2.max有2个正数 ans = max1 * min1 * min2

3.max有1个正数 ans = max1 * min1 * min2

4.max全是负数 ans = max1 * min1 * min2

所以答案就是max(max1 * max2 * max3, max1 * min1 * min2)

class Solution(object):
    def maximumProduct(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        min1 = float('inf')
        min2 = float('inf')
        max1 = float('-inf')
        max2 = float('-inf')
        max3 = float('-inf')
        
        for value in nums:
            if value <= min1:
                min2 = min1
                min1 = value
            elif value <= min2:
                min2 = value
            
            if value >= max1:
                max3 = max2
                max2 = max1
                max1 = value
            elif value >= max2:
                max3 = max2
                max2 = value
            elif value >= max3:
                max3 = value
        
        return max(min1 * min2 * max1, max1 * max2 * max3)

 

posted @ 2020-07-15 21:05  whatyouthink  阅读(120)  评论(0编辑  收藏  举报