LeetCode 题解工作台

三个数的最大乘积

给你一个整型数组 nums ,在数组中找出由三个数组成的最大乘积,并输出这个乘积。 示例 1: 输入: nums = [1,2,3] 输出: 6 示例 2: 输入: nums = [1,2,3,4] 输出: 24 示例 3: 输入: nums = [-1,-2,-3] 输出: -6 提示: 3 4 …

category

3

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·数学

bolt

答案摘要

我们先对数组 进行排序,接下来分两种情况讨论: - 如果 中全是非负数或者全是非正数,那么答案即为最后三个数的乘积,即 $\textit{nums}[n-1] \times \textit{nums}[n-2] \times \textit{nums}[n-3]$;

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

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

 

示例 1:

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

示例 2:

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

示例 3:

输入:nums = [-1,-2,-3]
输出:-6

 

提示:

  • 3 <= nums.length <= 104
  • -1000 <= nums[i] <= 1000
lightbulb

解题思路

方法一:排序 + 分类讨论

我们先对数组 nums\textit{nums} 进行排序,接下来分两种情况讨论:

  • 如果 nums\textit{nums} 中全是非负数或者全是非正数,那么答案即为最后三个数的乘积,即 nums[n1]×nums[n2]×nums[n3]\textit{nums}[n-1] \times \textit{nums}[n-2] \times \textit{nums}[n-3]
  • 如果 nums\textit{nums} 中既有正数也有负数,那么答案可能是两个最小负数和一个最大整数的乘积,即 nums[n1]×nums[0]×nums[1]\textit{nums}[n-1] \times \textit{nums}[0] \times \textit{nums}[1];也可能是最后三个数的乘积,即 nums[n1]×nums[n2]×nums[n3]\textit{nums}[n-1] \times \textit{nums}[n-2] \times \textit{nums}[n-3]

最后返回两种情况的最大值即可。

时间复杂度 O(n×logn)O(n \times \log n),空间复杂度 O(logn)O(\log n)。其中 nn 为数组 nums\textit{nums} 的长度。

1
2
3
4
5
6
7
class Solution:
    def maximumProduct(self, nums: List[int]) -> int:
        nums.sort()
        a = nums[-1] * nums[-2] * nums[-3]
        b = nums[-1] * nums[0] * nums[1]
        return max(a, b)
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Clarifies array length limits and negative number handling.

  • question_mark

    Asks if the candidate product combinations cover all edge cases.

  • question_mark

    Checks for efficient handling without unnecessary nested loops.

warning

常见陷阱

外企场景
  • error

    Ignoring the effect of negative numbers on the maximum product.

  • error

    Assuming the three largest numbers always produce the maximum.

  • error

    Not handling small arrays of exactly three elements properly.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Find the maximum product of k numbers for k > 3 in an array.

  • arrow_right_alt

    Return the triplet of numbers, not just the product, that produces the maximum.

  • arrow_right_alt

    Compute the maximum product in a stream of numbers without storing all elements.

help

常见问题

外企场景

三个数的最大乘积题解:数组·数学 | LeetCode #628 简单