题目
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
Note:
The length of the given array will be in range [3,104] and all elements are in the range [-1000, 1000].
Multiplication of any three numbers in the input won’t exceed the range of 32-bit signed integer.
理解
这题意思很清楚,逻辑也很简单,就是找到乘积结果最大的三个数,然后将结果输出。需要注意的是结果可能是两个负数一个正数的组合,这算是个小坑。
代码
class Solution:
def maximumProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
num = sorted(nums)
num.reverse()
max1 = num[0]
max2 = num[1]
max3 = num[2]
min1 = num[-1]
min2 = num[-2]
if min1 * min2 * max1 > max1 * max2 * max3:
return min1 * min2 * max1
else:
return max1 * max2 * max3
这里要感谢小嘎嘎,向她学习了list的sorted和reverse用法,之前我自己写的时候是很笨的自己遍历了一遍找最大数。这里可以看到除了找到最大的三个正数外,我们还需找到绝对值最大的两个负数,然后判断三正数乘积大还是两负数和最大正数乘积大即可。