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
nare[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
nare[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
nare[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
Thinking
The product of two digits is maximized by the largest and second-largest digits, independent of order. Track \(a \ge b\) while peeling digits; there is no need to store and sort them.
After \(O(\log n)\) digits, return \(a \cdot b\).
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 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
1 2 3 4 5 6 7 8 9 10 11 12 | |
1 2 3 4 5 6 7 8 9 10 11 12 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |