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
The Master Forger's Strategy๐ŸŽฏ Maximum StrategyFind first digit โ‰  9Transform ALL instances โ†’ 9Maximize leftmost impact!๐ŸŽฏ Minimum StrategyIf 1st digit > 1: change to 1Else: find 1st digit > 1, change to 0Minimize without zero-prefix!Example: num = 432Maximum:432โ†’932Minimum:432โ†’132Difference: 932 - 132 = 800
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!
Asked in
Google 25 Amazon 18 Microsoft 12 Apple 8
23.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen