代码一:
1 class Solution(object): 2 def maximumProduct(self, nums): 3 """ 4 :type nums: List[int] 5 :rtype: int 6 """ 7 # 降序排列 8 nums.sort(reverse=True) 9 return max(nums[0] * nums[1] * nums[2], nums[0] * nums[1] * nums[-1], nums[0] * nums[-1] * nums[-2])
代码二:
1 class Solution(object): 2 def maximumProduct(self, nums): 3 """ 4 :type nums: List[int] 5 :rtype: int 6 """ 7 # 处理nums中全是负数的情况 8 ans = 1 9 if max(nums) < 0: 10 for i in range(3): 11 ans *= max(nums) 12 nums.remove(max(nums)) 13 return ans 14 temp = [] 15 # 取两个绝对值最大的负数 16 for i in range(2): 17 if min(nums) < 0: 18 temp.append(min(nums)) 19 nums.remove(min(nums)) 20 temp.append(max(nums)) 21 nums.remove(max(nums)) 22 j = 0 23 while j < 2 and len(nums) != 0: 24 temp.append(max(nums)) 25 nums.remove(max(nums)) 26 j += 1 27 # 按绝对值大小降序排列 28 temp.sort(key=abs, reverse=True) 29 if len(temp) == 3: 30 return temp[0] * temp[1] * temp[2] 31 else: 32 ans = temp[0] * temp[1] 33 for i in range(2, len(temp)): 34 if ans > 0 and temp[i] > 0: 35 return ans * temp[i] 36 elif ans < 0 and temp[i] < 0: 37 return ans * temp[i] 38 return ans