628. Maximum Product of Three Numbers(easy)
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
注意是会有负数
1 暴力破解
考虑4种情况:
nums里只有三个数时:直接返回这三个数的乘积,啥都不用考虑
nums里有》4个数时考虑:
只有一个正数,》3个负数时:返回 最小的两个负数和正数的乘积保证乘积为最大正数
有两个正数时:说明必须乘一个负数,那就只能乘最大负数保证乘积为最大负数
在有三个以上正数时:考虑2负1正,3正哪个比较大
class Solution:
def maximumProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
length = len(nums)
sortnum = sorted(nums)
if length == 3:return nums[0]*nums[1]*nums[2]
neg = [i for i in sortnum if i < 0]
pos = [i for i in sortnum if i >=0]
if len(neg) == 1 or len(neg) == 0:return sortnum[-1]*sortnum[-2]*sortnum[-3]
elif len(pos) == 1: return neg[0] * neg[1] * pos[-1]
elif len(neg) >= 2:
negpro = neg[0] * neg[1] * pos[-1]
pospro = pos[-1] * pos[-2] * pos[-3]
if(negpro > pospro):return negpro
else:return pospro
Runtime: 124 ms, faster than 27.38% of Python3