Problem Description
Given a positive integer num, which consists only of the digits 6 and 9, the goal is to obtain the maximum possible number by changing at most one digit. The allowed operation is to switch a 6 to a 9 (or vice versa), but to maximize the overall value, we will change the first occurrence of 6 to 9.
Key Insights
- The maximum number is achieved by maximizing the leftmost digits.
- Changing a 6 to a 9 has the most impact when done at the earliest (leftmost) occurrence.
- Only one digit is allowed to change, so after finding the first 6, we stop.
Space and Time Complexity
Time Complexity: O(n), where n is the number of digits in the number (n is small based on the constraints).
Space Complexity: O(n), since we convert the integer to a string or list for easier manipulation.
Solution
The approach is as follows:
- Convert the integer to a string (or an array of characters) so that we can iterate through each digit.
- Traverse the string from left to right.
- When you encounter the first instance of '6', change it to '9' and break out of the loop, because only one change is allowed.
- Convert the modified string back to an integer and return it.
This greedy algorithm ensures that we maximize the numerical value by prioritizing the leftmost possible change. The small size of the input guarantees that the solution is efficient.