Intuition¶
The largest product of two digits is the product of the two largest digits in
n (allowing the same digit twice if it appears twice). Track the top two
digits while extracting them one by one.
Approach: Track Top Two Digits¶
- Initialize
firstMaxandsecondMaxto 0. - While
n > 0, takedigit = n % 10: - If
digit > firstMax, shiftfirstMaxintosecondMaxand updatefirstMax. - Else if
digit > secondMax, updatesecondMax. - Return
firstMax * secondMax.
Complexity¶
- Time complexity: $$O(\log n)$$ — one step per digit of
n. - Space complexity: $$O(1)$$.
Code¶
Go¶
func maxProduct(n int) int {
firstMax, secondMax := 0, 0
for n > 0 {
digit := n % 10
if digit > firstMax {
firstMax, secondMax = digit, firstMax
} else if digit > secondMax {
secondMax = digit
}
n /= 10
}
return firstMax * secondMax
}