LeetCode 题解工作台
三个数的最大乘积
给你一个整型数组 nums ,在数组中找出由三个数组成的最大乘积,并输出这个乘积。 示例 1: 输入: nums = [1,2,3] 输出: 6 示例 2: 输入: nums = [1,2,3,4] 输出: 24 示例 3: 输入: nums = [-1,-2,-3] 输出: -6 提示: 3 4 …
3
题型
5
代码语言
3
相关题
当前训练重点
简单 · 数组·数学
答案摘要
我们先对数组 进行排序,接下来分两种情况讨论: - 如果 中全是非负数或者全是非正数,那么答案即为最后三个数的乘积,即 $\textit{nums}[n-1] \times \textit{nums}[n-2] \times \textit{nums}[n-3]$;
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路
题目描述
给你一个整型数组 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
解题思路
方法一:排序 + 分类讨论
我们先对数组 进行排序,接下来分两种情况讨论:
- 如果 中全是非负数或者全是非正数,那么答案即为最后三个数的乘积,即 ;
- 如果 中既有正数也有负数,那么答案可能是两个最小负数和一个最大整数的乘积,即 ;也可能是最后三个数的乘积,即 。
最后返回两种情况的最大值即可。
时间复杂度 ,空间复杂度 。其中 为数组 的长度。
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)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.