leetcode 628. Maximum Product of Three Numbers
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.
这个题目本质上是一个数学题,需要细心观察才可以得到答案,考虑输入数据分布的几种情形:
(1)全部是正数, 答案必然是最大的三个数组合。
(2)全部是负数,答案和(1)同。
(3)既存在正数,又存在负数的情形,数组排序后的结果分为三种情形:
A、负,正,正,。。。=》最大数是三个最大数相乘。
B、负,负,正,。。。=〉最大数是:max【(负x负x最大的正数),三个最大的正数相乘(如果有三个正数的话)】
C、负,负,负,。。。正。。。。=》最大数和B同。
因此,总结起来,结果就是:
nums.sort() a = nums[-1] * nums[-2] * nums[-3] b = nums[0] * nums[1] * nums[-1] return max(a,b)
本质上是贪心。这种题目专门考察思维的完备性。
如果不用排序,则类似堆排序思想:
class Solution(object): def maximumProduct(self, nums): """ :type nums: List[int] :rtype: int """ max3, max2, max1 = float('-inf'), float('-inf'), float('-inf') min2, min1 = float('inf'), float('inf') for n in nums: if n > max1: if n > max3: max3, max2, max1 = n, max3, max2 elif n > max2: max3, max2, max1 = max3, n, max2 else: max3, max2, max1 = max3, max2, n if n < min2: if n < min1: min1, min2 = n, min1 else: min1, min2 = min1, n return max(max3*max2*max1, min1*min2*max3)
可以用python里现有的库:
class Solution(object): def maximumProduct(self, nums): """ :type nums: List[int] :rtype: int """ a, b = heapq.nlargest(3, nums), heapq.nsmallest(2, nums) return max(a[0] * a[1] * a[2], b[0] * b[1] * a[0])
补充:
>>> import heapq >>> nums=[21312,12211,211,3,12,212123] >>> heapq.nlargest(3, nums) [212123, 21312, 12211] >>> heapq.nsmallest(3, nums) [3, 12, 211]
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
2017-04-06 bleve搜索引擎源码分析之索引——mapping真复杂啊
2017-04-06 我的vim 配置——nerdtree、ack vim、vim sneak