[LeetCode] Maximum Product of Two Digits

3536. Maximum Product of Two Digits

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
int maxProduct(int n) {
vector<int> freq(10);
while(n) {
freq[n%10]++;
n /= 10;
}
int res = 0;
for(int i = 1; i < 10; i++) {
if(!freq[i]) continue;
freq[i]--;
for(int j = i; j < 10; j++) if(freq[j]) res = max(res, i * j);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/05/04/PS/LeetCode/maximum-product-of-two-digits/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.