Editorial
Solution walkthrough
Review the explanation, then compare the reference implementation.
Video explanation
Solution
Intuition
Changing a six to a nine increases the number, while changing a nine to a six decreases it. Among the available sixes, the leftmost has the greatest place value, so its change gives the largest possible gain.
Approach
Convert the number into a mutable sequence of decimal digits. Scan from left to right, replace the first 6 with 9, and stop so at most one digit changes. Join the digits and convert them back to an integer. If every digit is already nine, leave the number unchanged because the operation is optional.
class Solution:
def maximum69Number (self, num: int) -> int:
num = list(str(num))
for i in range(len(num)):
if num[i] == '6':
num[i] = '9'
break
return int("".join(num))Complexity analysis
For d decimal digits, converting, scanning, changing the first 6, and joining takes O(d) time and O(d) auxiliary space.
