
3536: Maximum Product of Two Digits
Problem Statement
Given a positive integer n
, return the maximum product of any two digits in n
. You may
use the same digit twice if it appears more than once.
Example 1
Input: n = 31
Output: 3
Explanation: Possible product is 3 × 1 = 3
Example 2
Input: n = 22
Output: 4
Explanation: Possible product is 2 × 2 = 4
Example 3
Input: n = 124
Output: 8
Explanation: Possible product is 2 × 4 = 8
Approach 1: Digit Extraction & Sorting (Optimal)
Extract digits, sort them, and calculate product of largest two digits.
Algorithm Steps
- Convert number to string to extract digits
- Convert characters to integers
- Sort digits in descending order
- Return product of first two digits
Complexity Analysis
Time Complexity | Space Complexity |
---|---|
O(d log d) | O(d) |
class maxProduct {
public:
int maxProduct(int n) {
string s = to_string(n);
if(s.size() < 2) return 0;
vector<int> digits;
for(char c : s) {
digits.push_back(c - '0');
}
sort(digits.rbegin(), digits.rend());
return digits[0] * digits[1];
}
};
class maxProduct {
public int maxProduct(int n) {
String s = Integer.toString(n);
if(s.length() < 2) return 0;
int[] digits = new int[s.length()];
for(int i=0; ilength(); i++){
digits[i] = s.charAt(i) - '0';
}
Arrays.sort(digits);
int len = digits.length;
return digits[len-1] * digits[len-2];
}
}
class maxProduct:
def maxProduct(self, n: int) -> int:
digits = list(map(int, str(n)))
if len(digits) < 2:
return 0
digits.sort(reverse=True)
return digits[0] * digits[1]
Edge Cases and Special Considerations
Key edge cases to consider when implementing your solution:
1. Single Digit Input
Input: 5 → Output: 0
Explanation: Not enough digits to form product
2. Multiple Zeros
Input: 100 → Output: 0
Explanation: Best product is 1 × 0 = 0
3. All Same Digits
Input: 999 → Output: 81
Explanation: 9 × 9 = 81
Frequently Asked Questions
1. Why does sorting work for this problem?
The two largest digits will always produce the maximum product when multiplied together. Sorting helps efficiently identify these digits.
2. How does this handle duplicate digits?
Sorting naturally groups duplicates. If a digit appears multiple times, the sorted array will have consecutive entries which are correctly considered.
3. What's the space complexity?
O(d) where d is number of digits, needed to store the digit array. This is efficient for numbers up to 1018 (18 digits).
4. Can we optimize further?
We can find the top two digits in O(d) time without full sorting, but for practical purposes (d ≤ 10), sorting is optimal.
5. How to handle invalid inputs?
The problem constraints guarantee valid positive integers. Code includes a check for minimum digit count as safety measure.