1. 程式人生 > 實用技巧 >628. Maximum Product of Three Numbers

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)