112 - 628 三个数的最大乘积

题目

给定一个整型数组,在数组中找出由三个数组成的最大乘积,并输出这个乘积。

示例 1:

输入: [1,2,3] 输出: 6

示例 2:

输入: [1,2,3,4] 输出: 24

注意:

  • 给定的整型数组长度范围是[3,104],数组中所有的元素范围是[-1000, 1000]。

  • 输入的数组中任意三个数的乘积不会超出32位有符号整数的范围。

解答

不就是。。找到数组中最大的三个数,然后乘一下么。。

排序?

https://leetcode-cn.com/problems/maximum-product-of-three-numbers/solution/628-san-ge-shu-de-zui-da-cheng-ji-by-en-zhao/

要多考虑一个,两个负数的情况。

func max(a, b int) int {
    if a > b {
        return a
    }
    return b
}
func maximumProduct(nums []int) int {
    sort.Ints(nums)
    return max(nums[0]*nums[1]*nums[len(nums)-1], nums[len(nums)-1]*nums[len(nums)-2]*nums[len(nums)-3])
}

Runtime: 64 ms, faster than 32.94% of Go online submissions for Maximum Product of Three Numbers.

Memory Usage: 6.3 MB, less than 100.00% of Go online submissions for Maximum Product of Three Numbers.

var maximumProduct = function(nums) {
  nums.sort((a, b) => a - b)
  const len = nums.length;
  return Math.max(nums[0] * nums[1] * nums[len - 1], nums[len - 1] * nums[
    len - 2] * nums[len - 3])
};

Runtime: 100 ms, faster than 59.67% of JavaScript online submissions for Maximum Product of Three Numbers.

Memory Usage: 38.3 MB, less than 100.00% of JavaScript online submissions for Maximum Product of Three Numbers.

class Solution:
    def maximumProduct(self, nums: List[int]) -> int:
        nums.sort()
        return max(nums[0] * nums[1]*nums[-1], nums[-1]*nums[-2]*nums[-3])

Runtime: 312 ms, faster than 74.30% of Python3 online submissions for Maximum Product of Three Numbers.

Memory Usage: 14.9 MB, less than 6.67% of Python3 online submissions for Maximum Product of Three Numbers.

Last updated

Was this helpful?