




Sponsored
Sponsored
This approach uses a simple greedy algorithm to find the first occurrence of the digit '6' and replaces it with '9'. This ensures that the number is maximized by making a change that increases the most significant portion of the number.
Time Complexity: O(n), where n is the number of digits in num.
Space Complexity: O(n) for storing the string representation of num.
1def maximum69Number(num):
2    num_str = str(num)
3    for i in range(len(num_str)):
4        if num_str[i] == '6':
5            num_str = num_str[:i] + '9' + num_str[i+1:]
6            break
7    return int(num_str)
8
9# Example Usage
10print(maximum69Number(9669))The Python implementation converts the number to a string. It finds the first occurrence of '6' and replaces it with '9'. Finally, it converts the updated string back to an integer.
This approach works directly with the number without converting it to a string. We find the first '6' from the leftmost side by using basic mathematical operations (division and modulo). We can calculate the position and change the digit using arithmetic transformations to make this efficient.
Time Complexity: O(1), as we have at most 4 digits to check.
Space Complexity: O(1), using constant space for computations.
1
JavaScript uses similar arithmetic functions to manipulate digit values directly. It avoids strings and focuses solely on mathematical adjustments.