Input:
num = 9669
Output:
9969
Explanation:
Changing the first digit results in 6669.
Changing the second digit results in 9969.
Changing the third digit results in 9699.
Changing the fourth digit results in 9666.
The maximum number is 9969.
Example 2:
1
2
3
4
5
Input:
num = 9996
Output:
9999
Explanation: Changing the last digit 6 to 9 results in the maximum number.
Example 3:
1
2
3
4
5
Input:
num = 9999
Output:
9999
Explanation: It is better not to apply any change.
Time: O(n) where n is number of characters in number string
Space: O(n)
Method 2 - Without string conversion - using modulo and division#
Consider the number 9696, when we want largest number it should be 9996 with 1 change:
1
2
9[6]96->9[9]96^^
But when we extract digits from number that is from right to left. So, first encountered 6 in number by modulo operator, will be last 6 digit from right. So, we need rightDigCount which counts number of digits to right of the last encountered ‘6’.
We will use digCount which tracks number of digits to right of any dig at some instance. So, as soon as we encounter 6, we set rightDigCount = digCount.
Now, in example above, rightDigitCount = 2.
As difference between 6 and 9 is 3, our answer is:
1
2
ans = num +3*(10^ rigitDigitCount)ans =9696+300=9999