LeetCode (628. Maximum product of three numbers)
Given an integer array, find the largest product consisting of three numbers in the array, and output this product.
Example 1:
Input: [1,2,3]
Output: 6
Example 2:Input: [1,2,3,4]
Output: 24
Note:The length range of the given integer array is [3,104], and the range of all elements in the array is [-1000, 1000].
The product of any three numbers in the input array will not exceed the range of 32-bit signed integers.
Link: topic linkanswer:
class Solution: def maximumProduct(self, n: List[int]) -> int: ## 先倒序排序,对正数和负数分开判断 n.sort(reverse=True) ## 找负数的个数,不可能取负数的三个值,所以只可能取负数的两个值 count = 0 ## 判断倒序后的n的前面三个和最后两个负数的大小 for i in range(len(n)): if n[i]<0: count = len(n)-i if count>=2:a = n[-count:][-2:] break b = n[0]*n[1]*n[2] if count >=2: c = n[0]*a[-2]*a[-1] if c>=b:return c return b