-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy path三个数的最大乘积.py
23 lines (21 loc) · 1.11 KB
/
三个数的最大乘积.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#-*- coding:utf8 -*-
#author : Lenovo
#date: 2018/9/6
#返回一个列表中三个数的最大乘积,大概有下面几种情况。
#1,全部为正数,排序后最后三个数相乘
#2。排序后的最后三个数中有两个负数,那么这个列表前两个元素也是负数 由于负负得正 结果为 0*1*-1 和-3*-2*-1中的最大值
#
def maximumProduct(nums):
"""
:type nums: List[int]
:rtype: int
"""
nums=sorted(nums)
print(nums)
if nums[-2]<0:
return nums[0]*nums[1]*nums[-1]
if nums[1]<0:
return max(nums[-1]*nums[-2]*nums[-3],nums[0]*nums[1]*nums[-1])
return nums[-1]*nums[-2]*nums[-3]
res=maximumProduct([722,634,-504,-379,163,-613,-842,-578,750,951,-158,30,-238,-392,-487,-797,-157,-374,999,-5,-521,-879,-858,382,626,803,-347,903,-205,57,-342,186,-736,17,83,726,-960,343,-984,937,-758,-122,577,-595,-544,-559,903,-183,192,825,368,-674,57,-959,884,29,-681,-339,582,969,-95,-455,-275,205,-548,79,258,35,233,203,20,-936,878,-868,-458,-882,867,-664,-892,-687,322,844,-745,447,-909,-586,69,-88,88,445,-553,-666,130,-640,-918,-7,-420,-368,250,-786])
print(res)