You are given a positive integer num consisting only of the digits 6 and 9. You are allowed to change at most one digit (turning a 6 into a 9, or a 9 into a 6). Your objective is to return the maximum possible number you can create.
This is a classic entry-level warmup problem. Interviewers use it to assess basic string manipulation and greedy logic. It quickly verifies if a candidate understands positional math—specifically, that changing a digit in a higher place value (further to the left) yields a much larger overall number than changing a digit on the right.
This problem uses a strict Greedy pattern combined with String Traversal.
To maximize the number, you want to increase its value. The only way to increase it is to change a 6 to a 9. Because place value dictates magnitude, you must greedily change the very first 6 you encounter from left to right. Converting the integer to a string or character array makes this left-to-right scan trivial.
num = 9669
"9669".9. Leave it.6. Change it to 9! We have used our one allowed change. Break the loop."9969".9969.What if the number is 9999?
6 is found.9999 (changing a 9 to a 6 would decrease the value, so doing nothing is the optimal choice).A common mistake is iterating from right to left (using modulo 10 math) and changing the first 6 encountered, which actually changes the least significant 6. For 9669, this would yield 9699, which is smaller than 9969. If you solve it using pure math (without strings), you must track the index of the highest 6 you've seen and apply the math addition + 3 * Math.pow(10, highest_six_index) at the very end.
For the Maximum 69 Number coding problem, using string manipulation (String.valueOf(), replaceFirst(), or character arrays) is perfectly acceptable and results in a 3-line solution. However, if the interviewer asks for an space solution without string conversions, be prepared to write the modulo loop that tracks the multiplier offset of the leftmost 6.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Maximum Difference by Remapping a Digit | Easy | Solve | |
| Distribute Money to Maximum Children | Easy | Solve | |
| Maximum Swap | Medium | Solve | |
| Max Difference You Can Get From Changing an Integer | Medium | Solve | |
| Minimum Moves to Reach Target Score | Medium | Solve |