LeetCode 题解工作台
两个数字的最大乘积
给定一个正整数 n 。 返回 任意两位数字 相乘所得的 最大 乘积。 注意: 如果某个数字在 n 中出现多次,你可以多次使用该数字。 示例 1: 输入: n = 31 输出: 3 解释: n 的数字是 [3, 1] 。 任意两位数字相乘的结果为: 3 * 1 = 3 。 最大乘积为 3。 示例 2:…
2
题型
5
代码语言
3
相关题
当前训练重点
简单 · 数学·结合·排序
答案摘要
我们用两个变量 和 来记录当前最大的数字和次大的数字。我们遍历 的每一位数字,如果当前数字大于 ,则将 赋值为 ,然后将 赋值为当前数字;否则,如果当前数字大于 ,则将 赋值为当前数字。最后返回 $a \times b$ 即可。 时间复杂度 $O(\log n)$,其中 是输入数字的大小。空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数学·结合·排序 题型思路
题目描述
给定一个正整数 n。
返回 任意两位数字 相乘所得的 最大 乘积。
注意:如果某个数字在 n 中出现多次,你可以多次使用该数字。
示例 1:
输入: n = 31
输出: 3
解释:
n的数字是[3, 1]。- 任意两位数字相乘的结果为:
3 * 1 = 3。 - 最大乘积为 3。
示例 2:
输入: n = 22
输出: 4
解释:
n的数字是[2, 2]。- 任意两位数字相乘的结果为:
2 * 2 = 4。 - 最大乘积为 4。
示例 3:
输入: n = 124
输出: 8
解释:
n的数字是[1, 2, 4]。- 任意两位数字相乘的结果为:
1 * 2 = 2,1 * 4 = 4,2 * 4 = 8。 - 最大乘积为 8。
提示:
10 <= n <= 109
解题思路
方法一:找到最大和次大数字
我们用两个变量 和 来记录当前最大的数字和次大的数字。我们遍历 的每一位数字,如果当前数字大于 ,则将 赋值为 ,然后将 赋值为当前数字;否则,如果当前数字大于 ,则将 赋值为当前数字。最后返回 即可。
时间复杂度 ,其中 是输入数字的大小。空间复杂度 。
class Solution:
def maxProduct(self, n: int) -> int:
a = b = 0
while n:
n, x = divmod(n, 10)
if a < x:
a, b = x, a
elif b < x:
b = x
return a * b
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(k log k) for sorting, where k is the number of digits, or O(k) for the single-pass optimization. Space complexity is O(k) to store digits or O(1) for the single-pass variant. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Check if candidate handles repeated digits correctly.
- question_mark
Listen for sorting or digit extraction as a natural optimization.
- question_mark
See if the candidate considers single-pass vs full sort trade-offs.
常见陷阱
外企场景- error
Forgetting that digits can repeat and pair with themselves.
- error
Attempting full brute-force without considering sorting or optimization.
- error
Mismanaging integer-to-digit conversion or edge cases like n having only two digits.
进阶变体
外企场景- arrow_right_alt
Compute maximum product of three digits instead of two.
- arrow_right_alt
Restrict digits to even numbers only for the product.
- arrow_right_alt
Return the digits forming the maximum product instead of the product itself.