leetcode628-- Maximum Product of Three Numbers

# 小郑之家~

### 题目

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

Example 1:

Input: [1,2,3]
Output: 6

Example 2:

Input: [1,2,3,4]
Output: 24



• case2 全是负数

• case3 负数不少于两个

class Solution(object):
def maximumProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""

# 特别情况
if len(nums) == 3:
return nums[0]*nums[1]*nums[2]

nums.sort()
return max(nums[0]*nums[1]*nums[-1], nums[-1]*nums[-2]*nums[-3])



class Solution(object):
def maximumProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""

if len(nums) ==3:
return nums[0]*nums[1]*nums[2]

mx1 = float("-inf")
mx2 = float("-inf")
mx3 = float("-inf")

mi1 = float("inf")
mi2 = float("inf")

for x in nums:

if x> mx1:
mx3 =mx2
mx2 = mx1
mx1 = x
elif x>mx2:
mx3 = mx2
mx2 = x
elif x>mx3:
mx3 = x

if x< mi1:
mi2 = mi1
mi1 =x
elif x< mi2:
mi2 = x

return max(mi1*mi2*mx1, mx1*mx2*mx3)



class Solution(object):
def maximumProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""

if len(nums) ==3:
return nums[0]*nums[1]*nums[2]

mx1 = float("-inf")
mx2 = float("-inf")
mx3 = float("-inf")

mi1 = float("inf")
mi2 = float("inf")

for x in nums:

if x> mx1:
mx1, mx2, mx3 = x, mx1, mx2
elif x>mx2:
mx2, mx3 = x, mx2
elif x>mx3:
mx3 = x
if x< mi1:
mi1, mi2 = x, mi1
elif x< mi2:
mi2 = x

return max(mi1*mi2*mx1, mx1*mx2*mx3)