628. Maximum Product of Three Numbers
阿新 • • 發佈:2020-07-15
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 innums: if value <= min1: min2 = min1 min1 = value elif value <= min2: min2 = value if value >= max1: max3 = max2 max2 = max1 max1 = valueelif value >= max2: max3 = max2 max2 = value elif value >= max3: max3 = value return max(min1 * min2 * max1, max1 * max2 * max3)