Maximum 69 Number Problem
#1323
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 1323.
You are given a positive integer num consisting only of digits 6 and 9.
Return the maximum number you can get by changing at most one digit (6 becomes 9, and 9 becomes 6).
Example 1:
Input: num = 9669
Output: 9969
Explanation:
Changing the first digit results in 6669.
Changing the second digit results in 9969.
Changing the third digit results in 9699.
Changing the fourth digit results in 9666.
The maximum number is 9969.
Example 2:
Input: num = 9996
Output: 9999
Explanation: Changing the last digit 6 to 9 results in the maximum number.
Example 3:
Input: num = 9999
Output: 9999
Explanation: It is better not to apply any change.
Constraints:
1 <= num <= 10^4numconsists of only6and9digits.
Solution
Approach: Change the Leftmost 6
Changing a 9 into a 6 only makes the number smaller, so the only useful move is turning a 6 into a 9. A digit further left is worth more, so the gain is largest for the leftmost 6: turning it into a 9 beats any change to the digits after it.
So we write the number as a string, replace its first 6 with a 9, and convert it back. If there is no 6 at all (like 9999), the number is already the largest possible and stays as it is.
Complexity: O(d) time and space, where d is the number of digits (at most 4 here).
class Solution:
def maximum69Number(self, num: int) -> int:
# Turning the leftmost 6 into a 9 gains the most; with no 6, change nothing.
return int(str(num).replace("6", "9", 1))