LeetCode 题解工作台

两个数字的最大乘积

给定一个正整数 n 。 返回 任意两位数字 相乘所得的 最大 乘积。 注意: 如果某个数字在 n 中出现多次,你可以多次使用该数字。 示例 1: 输入: n = 31 输出: 3 解释: n 的数字是 [3, 1] 。 任意两位数字相乘的结果为: 3 * 1 = 3 。 最大乘积为 3。 示例 2:…

category

2

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 数学·结合·排序

bolt

答案摘要

我们用两个变量 和 来记录当前最大的数字和次大的数字。我们遍历 的每一位数字,如果当前数字大于 ,则将 赋值为 ,然后将 赋值为当前数字;否则,如果当前数字大于 ,则将 赋值为当前数字。最后返回 $a \times b$ 即可。 时间复杂度 $O(\log n)$,其中 是输入数字的大小。空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数学·结合·排序 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给定一个正整数 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
lightbulb

解题思路

方法一:找到最大和次大数字

我们用两个变量 aabb 来记录当前最大的数字和次大的数字。我们遍历 nn 的每一位数字,如果当前数字大于 aa,则将 bb 赋值为 aa,然后将 aa 赋值为当前数字;否则,如果当前数字大于 bb,则将 bb 赋值为当前数字。最后返回 a×ba \times b 即可。

时间复杂度 O(logn)O(\log n),其中 nn 是输入数字的大小。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
10
11
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
speed

复杂度分析

指标
时间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
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

两个数字的最大乘积题解:数学·结合·排序 | LeetCode #3536 简单