Change digits of an integer twice to maximize the difference between the largest and smallest possible values.
Problem
You are given a non-negative integer num. You may perform the following operation twice, independently:
- Pick one digit in
numand replace every occurrence of that digit with another digit from0to9.
After one replacement, the resulting number must still be a valid integer representation; in particular, it cannot have leading zeros unless the number itself is 0.
Your goal is to maximize the difference between the value obtained by making a best possible replacement to create a large number and the value obtained by making a best possible replacement to create a small number.
Return that maximum difference.
Notes
- You may choose different digits for the maximizing and minimizing transformations.
- Replacements apply to all occurrences of the chosen digit.
- The original number is given in decimal form.
Input Format
- A single integer
num.
You may treat it as a decimal string of digits for the purpose of replacement.
Output Format
- Return one integer: the maximum possible difference between the best larger transformed value and the best smaller transformed value.
Constraints
0 <= num <= $10^{8}$numcontains no leading zeros unless it is exactly0.- Any replacement must keep the number a valid decimal integer representation.
Example 1
Input
num = 555
Output
888
Explanation
To maximize, change all 5 to 9 to get 999. To minimize, changing 5 to 1 gives 111. The difference is 999 - 111 = 888.
Example 2
Input
num = 9
Output
8
Explanation
The best maximum value is 9 itself. The smallest valid value is 1, obtained by changing 9 to 1. The difference is 8.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.