8/7 每日一題(找出最大成積)
Given an integer array nums, find three numbers whose product is maximum and return the maximum product.
Example 1:
Input: nums = [1,2,3] Output: 6
Example 2:
Input: nums = [1,2,3,4] Output: 24
Example 3:
Input: nums = [-1,-2,-3] Output: -6
Constraints:
3 <= nums.length <= 104-1000 <= nums[i] <= 1000
class Solution:
def maximumProduct(self, nums: List[int]) -> int:
nums.sort()
b=nums[0]*nums[1]*nums[-1]
c=nums[-1]*nums[-2]*nums[-3]
return max(b,c)
---------------參考解答
class Solution:
def maximumProduct(self, nums: List[int]) -> int:
pos=heapq.nlargest(3,nums) #找出nums中3個最大值加入pos
neg=heapq.nsmallest(2,nums) #找出nums中2個最小值加入neg return max(neg[0]*neg[1]*pos[0],pos[0]*pos[1]*pos[2])
標籤: leetcode

0 個意見:
張貼留言
訂閱 張貼留言 [Atom]
<< 首頁