Maximum 69 Number - Problem

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).

Input & Output

Example 1 — Basic Case with 6
$ Input: num = 9669
Output: 9969
💡 Note: Change the first 6 to 9: 9669 → 9969. This gives maximum value since 6→9 increases the hundreds place.
Example 2 — All 9s
$ Input: num = 9996
Output: 9999
💡 Note: Change the last 6 to 9: 9996 → 9999. Only one 6 present, changing it maximizes the number.
Example 3 — No 6s present
$ Input: num = 9999
Output: 9996
💡 Note: No 6s to change to 9s. Change the rightmost 9 to 6: 9999 → 9996 for maximum with constraint.

Constraints

  • 1 ≤ num ≤ 104
  • num consists only of 6 and 9 digits

Visualization

Tap to expand
Maximum 69 Number INPUT Number: 9669 9 pos 0 6 pos 1 6 pos 2 9 pos 3 Constraints: - Only digits 6 and 9 - Change at most 1 digit Goal: Maximize the number ALGORITHM STEPS 1 Convert to String "9669" for digit access 2 Scan Left to Right Find FIRST '6' digit 9 6 FOUND! 6 9 3 Change 6 to 9 First 6 at position 1 6 9 4 Return Result Convert back to int Time: O(n), Space: O(n) FINAL RESULT Before: 9 6 6 9 After: 9 9 6 9 Output: 9969 OK - Maximum! Key Insight: To maximize a number, change the leftmost (most significant) digit 6 to 9. The first 6 from the left has the highest place value, so changing it gives the maximum increase. TutorialsPoint - Maximum 69 Number | Greedy First-6-to-9 Approach
Asked in
Google 15 Amazon 12 Microsoft 8
25.0K Views
Medium Frequency
~8 min Avg. Time
892 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