Skip to content

3536. Maximum Product of Two Digits

Description

You are given a positive integer n.

Return the maximum product of any two digits in n.

Note: You may use the same digit twice if it appears more than once in n.

 

Example 1:

Input: n = 31

Output: 3

Explanation:

  • The digits of n are [3, 1].
  • The possible products of any two digits are: 3 * 1 = 3.
  • The maximum product is 3.

Example 2:

Input: n = 22

Output: 4

Explanation:

  • The digits of n are [2, 2].
  • The possible products of any two digits are: 2 * 2 = 4.
  • The maximum product is 4.

Example 3:

Input: n = 124

Output: 8

Explanation:

  • The digits of n are [1, 2, 4].
  • The possible products of any two digits are: 1 * 2 = 2, 1 * 4 = 4, 2 * 4 = 8.
  • The maximum product is 8.

 

Constraints:

  • 10 <= n <= 109

Solutions

SolutionΒ 1: Find the Largest and Second Largest Digits

We keep two variables, \(a\) andΒ \(b\), to record the current largest and second‑largest digits, respectively. We iterate over every digit of \(n\); if the current digit is larger thanΒ \(a\), we assignΒ \(b\) the value ofΒ \(a\) and then setΒ \(a\) to the current digit. Otherwise, if the current digit is larger thanΒ \(b\), we setΒ \(b\) to the current digit. Finally, we return \(a \times b\).

The time complexity isΒ \(O(\log n)\), whereΒ \(n\) is the input number, and the space complexity isΒ \(O(1)\).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
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
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
    public int maxProduct(int n) {
        int a = 0, b = 0;
        for (; n > 0; n /= 10) {
            int x = n % 10;
            if (a < x) {
                b = a;
                a = x;
            } else if (b < x) {
                b = x;
            }
        }
        return a * b;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
public:
    int maxProduct(int n) {
        int a = 0, b = 0;
        for (; n; n /= 10) {
            int x = n % 10;
            if (a < x) {
                b = a;
                a = x;
            } else if (b < x) {
                b = x;
            }
        }
        return a * b;
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
func maxProduct(n int) int {
    a, b := 0, 0
    for ; n > 0; n /= 10 {
        x := n % 10
        if a < x {
            b, a = a, x
        } else if b < x {
            b = x
        }
    }
    return a * b
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
function maxProduct(n: number): number {
    let [a, b] = [0, 0];
    for (; n; n = Math.floor(n / 10)) {
        const x = n % 10;
        if (a < x) {
            [a, b] = [x, a];
        } else if (b < x) {
            b = x;
        }
    }
    return a * b;
}

Comments