Maximum 69 Number - Problem

Imagine you have a special number made up of only 6s and 9s - like a digital display where some segments might be flipped! Your mission is to make this number as large as possible by flipping at most one digit.

๐Ÿ”„ The Rule: You can change exactly one digit:

  • 6 โ†’ 9 (increases the number)
  • 9 โ†’ 6 (decreases the number)

Goal: Return the maximum possible number you can achieve.

Example: Given 9669, you can change the first 6 to 9 to get 9969 - but is this optimal? ๐Ÿค”

Input & Output

example_1.py โ€” Basic Case
$ Input: num = 9669
โ€บ Output: 9969
๐Ÿ’ก Note: We can change the first 6 to 9 to get 9969, which is the maximum possible.
example_2.py โ€” All 9s
$ Input: num = 9996
โ€บ Output: 9969
๐Ÿ’ก Note: No 6s to change to 9, so we change the rightmost 9 to 6 to minimize the decrease.
example_3.py โ€” Single Digit
$ Input: num = 9
โ€บ Output: 6
๐Ÿ’ก Note: Only one digit available, and since it's 9, we change it to 6.

Constraints

  • 1 โ‰ค num โ‰ค 104
  • num consists only of digits 6 and 9
  • You can change at most one digit

Visualization

Tap to expand
The Digit Flipper Strategy๐ŸŽฏ Goal: Find the leftmost 6 and flip it to 9Why? Because leftmost digits contribute most to the final value!Example: 6999 โ†’ 9999 gives +3000, but 9996 โ†’ 9999 gives only +3Case 1: Has 6s9669FLIP!Case 2: All 9s9999FLIP LASTResult: 9969Maximized!9669 โ†’ 9969 (+300)Result: 9996Best possible9999 โ†’ 9996 (-3)๐Ÿ’ก Key: Leftmost changes have maximum impact!
Understanding the Visualization
1
Scan from Left
Start from the most significant digit - changes here have the biggest impact
2
Find First 6
The first 6 we encounter can be flipped to 9 for maximum gain
3
Flip and Return
Change that 6 to 9 and we're done - this gives us the maximum possible value
4
All 9s Case
If no 6s exist, flip the rightmost 9 to 6 to minimize the loss
Key Takeaway
๐ŸŽฏ Key Insight: The greedy approach works because changing the leftmost digit has the maximum impact on the final number value. Always prioritize the most significant positions!
Asked in
Google 15 Amazon 12 Microsoft 8 Apple 5
25.0K Views
Medium Frequency
~8 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen