#3536
Maximum Product of Two Digits
EasyMathSortingArraySorting
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Instead of checking all pairs, we can find the two largest digits and multiply them for the maximum product. This is efficient and quick.
⚙️
Algorithm
3 steps- 1Step 1: Convert the integer n to a list of its digits.
- 2Step 2: Identify the two largest digits in the list.
- 3Step 3: Return the product of these two digits.
solution.py3 lines
1def maxProduct(n):
2 digits = sorted([int(d) for d in str(n)])
3 return digits[-1] * digits[-2]ℹ
Complexity note: The complexity is O(n) because we only traverse the digits once to find the two largest.
- 1The maximum product comes from the two largest digits.
- 2Sorting can help quickly identify the largest elements.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.