tutorialcup
Maximum 69 Number Leetcode Solution
Problem Statement
In this problem, we are given a number made up of digits 6 or 9. We can replace one of a digit of this number and change this to another digit. i.e. we can replace a 6 to 9 or we can replace a 9 to 6. We have to output the maximum number we can get by at most one replace.
Example
num = 9669
9969
Explanation:
Changing the first digit results in 6669.
Changing the second digit results in 9969.
Similarly Changing the third digit results in 9699.
Changing the fourth digit results in 9666.
The maximum number is 9969.
9996
9999
Explanation:
Changing the last digit 6 to 9 results in the maximum number.
Approach
As we can replace a digit to make the number maximum, one thing we can understand here is that, we should replace 6 to 9 only, because 9 to 6 replace will make the number smaller.
Another thing we can understand here is, we should replace a digit leftmost as possible. Let's understand this thing with an example.
Suppose we have a number given, 6666
We have to replace a digit from 6 to 9 such that the formed number is maximum. If we replace the rightmost 6 then we get 6669.
If we replace the leftmost 6 then we get 9666 which is of course the maximum of all numbers gained by such replacement on this number.
Thus we will try to replace the leftmost 6. And if no 6 is present in given number e.g. 9999 then we will not perform any replace operation.
www.tutorialcup.com/leetcode-solutions/maximum-69-number-...
Maximum 69 Number Leetcode Solution
Problem Statement
In this problem, we are given a number made up of digits 6 or 9. We can replace one of a digit of this number and change this to another digit. i.e. we can replace a 6 to 9 or we can replace a 9 to 6. We have to output the maximum number we can get by at most one replace.
Example
num = 9669
9969
Explanation:
Changing the first digit results in 6669.
Changing the second digit results in 9969.
Similarly Changing the third digit results in 9699.
Changing the fourth digit results in 9666.
The maximum number is 9969.
9996
9999
Explanation:
Changing the last digit 6 to 9 results in the maximum number.
Approach
As we can replace a digit to make the number maximum, one thing we can understand here is that, we should replace 6 to 9 only, because 9 to 6 replace will make the number smaller.
Another thing we can understand here is, we should replace a digit leftmost as possible. Let's understand this thing with an example.
Suppose we have a number given, 6666
We have to replace a digit from 6 to 9 such that the formed number is maximum. If we replace the rightmost 6 then we get 6669.
If we replace the leftmost 6 then we get 9666 which is of course the maximum of all numbers gained by such replacement on this number.
Thus we will try to replace the leftmost 6. And if no 6 is present in given number e.g. 9999 then we will not perform any replace operation.
www.tutorialcup.com/leetcode-solutions/maximum-69-number-...