Maximum Product of Two Digits Problem
#3536
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3536.
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 <= 10^9
Solution
Approach: Largest Two Digits
The best product comes from the two largest digits of n (they may be equal digits at different positions). Scan the digits while keeping the largest, a, and the second largest, b: a bigger digit pushes a down into b, otherwise it may replace b. Return a * b.
Complexity: O(log n) time and O(1) extra space, where n is the input number.
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