Given an integer N, the task is to find the maximum difference after applying the given operation two times on the given integer.
The operation is defined as follows:
- Choose any digit (0-9) from N and replace all instance of the same digit with any other digit (0-9).
- N after the operation cannot have leading zeros and also it cannot be equal to zero.
Input : N = 777
Output : 888
Explanation: Select digit 7 and replace all it’s occurrences with 9 to get 999. similarly 111 can be obtained by replacing all occurrences of 7 with 1. Hence, the possible maximum difference is 888.
Input : N = 123456
Output : 820000
The numbers after two operation can be 923456 and 103456. Hence, the required maximum difference is 820000.
Explanation: Maximum difference can be obtained by subtraction of the maximum and the minimum number that can be obtained by the given operation on N.
- The maximum number can be obtained by picking the first digit of N from the left which is not equal to ‘9’ and replace all the instances of that digit into ‘9’.
- Finding the minimum number is a little bit tricky as N cannot have any leading zeros and also it cannot be equal to zero. If the first digit of N from the left is ‘1’, then find the first digit from the left which is greater than ‘1’ and replace all instances of that digit with ‘0’.
- Otherwise, if the first digit of N from the left is not equal to ‘1’, then choose that digit and replace all instances of that digit with ‘1’.
- Finally, return the difference between the minimum and maximum number as the answer.
Below is the implementation of the above approach:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.