3536. Maximum Product of Two Digits
- Math
- Greedy
TIME
O(d)
SPACE
O(1)
Intuition
Digits are non-negative, so the largest product of any two of them is simply the product of the two largest digits (using the same position isn't allowed, but a repeated value is, and tracking the top two by value handles that automatically since n >= 10 guarantees at least two digits).
Approach
- Scan the digits of
n, maintaining the largest (max1) and second-largest (max2) digit values seen. - Return
max1 * max2.
Complexity
- Time: O(d) where d = number of digits (at most 10)
- Space: O(1)
Edge Cases
- Repeated largest digit (e.g.
22) →max1andmax2both that value → squared - At least two digits always exist (
n >= 10) - A
0digit just never wins the top two unless forced; products stay correct
Code
class Solution:
def maxProduct(self, n: int) -> int:
"""
3536. Maximum Product of Two Digits
Time: O(d)
Space: O(1)
"""
max1 = max2 = -1 # two largest digit values
for ch in str(n):
d = int(ch)
if d >= max1:
max2 = max1
max1 = d
elif d > max2:
max2 = d
return max1 * max2/**
* 3536. Maximum Product of Two Digits
* Time: O(d)
* Space: O(1)
*/
class Solution {
public int maxProduct(int n) {
int max1 = -1, max2 = -1; // two largest digit values
while (n > 0) {
int d = n % 10;
if (d >= max1) {
max2 = max1;
max1 = d;
} else if (d > max2) {
max2 = d;
}
n /= 10;
}
return max1 * max2;
}
}