Maximum Difference by Remapping a Digit - Problem
You're given an integer num and Bob, a sneaky character, has the ability to remap exactly one digit (0-9) to any other digit of his choice.
Goal: Find the maximum possible difference between the largest and smallest numbers Bob can create by remapping digits.
Key Rules:
- Bob must remap exactly one digit type - all occurrences of that digit get replaced
- Bob can use different remapping strategies for maximum vs minimum values
- Leading zeros are allowed in the result
- Bob can remap a digit to itself (no change)
Example: For num = 11111, Bob can remap all 1's to 9's for maximum (99999) and all 1's to 0's for minimum (00000 = 0), giving difference = 99999.
Input & Output
example_1.py โ Basic Case
$
Input:
num = 123
โบ
Output:
820
๐ก Note:
For maximum: change first non-9 digit (1) to 9 โ 923. For minimum: change first digit (1) to 1 โ no change, so find first non-0,non-1 digit (2) and change to 0 โ 103. Difference: 923 - 103 = 820.
example_2.py โ All Same Digits
$
Input:
num = 555
โบ
Output:
888
๐ก Note:
For maximum: change 5 to 9 โ 999. For minimum: since first digit is 5 (not 1), change 5 to 1 โ 111. Difference: 999 - 111 = 888.
example_3.py โ Edge Case with 9s
$
Input:
num = 9321
โบ
Output:
8970
๐ก Note:
For maximum: first digit is already 9, next non-9 is 3, change to 9 โ 9921. For minimum: first digit is 9 (not 1), so change 9 to 1 โ 1321. Difference: 9921 - 1321 = 8600.
Constraints
- 1 โค num โค 108
- num does not contain any leading zeros
Visualization
Tap to expand
Understanding the Visualization
1
Scan for Maximum Impact
For maximum value, scan left-to-right to find the first digit that isn't already 9
2
Apply Maximum Transform
Transform all occurrences of that digit to 9 for maximum boost
3
Strategic Minimum Approach
For minimum, if first digit > 1, change to 1; else find first digit > 1 and change to 0
4
Calculate the Difference
The difference between these optimal transformations is our answer
Key Takeaway
๐ฏ Key Insight: Greedy works perfectly because digit position determines exponential value impact - optimizing the leftmost digits gives maximum benefit!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code