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:

    1. The length of the given array will be in range [3,104] and all elements are in the range [-1000, 1000].
    2. 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]

 

posted @   bonelee  阅读(163)  评论(2编辑  收藏  举报
编辑推荐:
· 记一次.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
点击右上角即可分享
微信分享提示