Maximum Difference by Remapping a Digit - Problem

You are given an integer num. You know that Bob will sneakily remap one of the 10 possible digits (0 to 9) to another digit.

Return the difference between the maximum and minimum values Bob can make by remapping exactly one digit in num.

Notes:

  • When Bob remaps a digit d1 to another digit d2, Bob replaces all occurrences of d1 in num with d2.
  • Bob can remap a digit to itself, in which case num does not change.
  • Bob can remap different digits for obtaining minimum and maximum values respectively.
  • The resulting number after remapping can contain leading zeroes.

Input & Output

Example 1 — Basic Case
$ Input: num = 123
Output: 900
💡 Note: For maximum: replace 1→9 to get 923. For minimum: replace 1→0 to get 023 (which is 23). Difference is 923 - 23 = 900.
Example 2 — All Same Digits
$ Input: num = 555
Output: 888
💡 Note: For maximum: replace 5→9 to get 999. For minimum: replace 5→1 to get 111. Difference is 999 - 111 = 888.
Example 3 — Already Has 9
$ Input: num = 9321
Output: 8600
💡 Note: For maximum: replace 3→9 to get 9921. For minimum: replace 9→1 to get 1321. Difference is 9921 - 1321 = 8600.

Constraints

  • 1 ≤ num ≤ 108

Visualization

Tap to expand
Maximum Difference by Remapping a Digit INPUT Given Number: 1 pos 0 2 pos 1 3 pos 2 Problem: Remap one digit to another Find MAX - MIN possible values after remapping Unique Digits: {1, 2, 3} num = 123 Original Value ALGORITHM STEPS 1 Find Maximum Remap first non-9 digit to 9 1 --> 9: 123 becomes 923 MAX = 923 2 Find Minimum Remap first digit to 0 1 --> 0: 123 becomes 023 MIN = 23 3 Calculate Difference MAX - MIN = Answer 923 - 23 = 900 4 Return Result Output: 900 Greedy: Always maximize/minimize by targeting leftmost digit FINAL RESULT Maximum Value 923 1 mapped to 9 Minimum Value 23 1 mapped to 0 DIFFERENCE 900 923 - 23 = 900 OK - Answer Verified Key Insight: For MAXIMUM: Find the first digit (from left) that is not 9, and remap it to 9. This maximizes the number. For MINIMUM: Remap the first digit to 0 (leading zeros are allowed). This minimizes the number. Greedy approach works because leftmost digits have the highest place value, giving maximum impact. TutorialsPoint - Maximum Difference by Remapping a Digit | Greedy - Smart Digit Selection
Asked in
Google 15 Microsoft 12 Amazon 8
18.5K Views
Medium Frequency
~15 min Avg. Time
542 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