Max Difference You Can Get From Changing an Integer - Problem

You are given an integer num. You will apply the following steps to num two separate times:

  • Pick a digit x (0 ≤ x ≤ 9).
  • Pick another digit y (0 ≤ y ≤ 9). Note y can be equal to x.
  • Replace all the occurrences of x in the decimal representation of num by y.

Let a and b be the two results from applying the operation to num independently.

Return the maximum difference between a and b.

Note that neither a nor b may have any leading zeros, and must not be 0.

Input & Output

Example 1 — Basic Case
$ Input: num = 555
Output: 888
💡 Note: To maximize: all digits are 5 (not 9), so replace 5→9 to get 999. To minimize: first digit is 5≠1, so replace 5→1 to get 111. Difference: 999 - 111 = 888
Example 2 — First Digit is 9
$ Input: num = 901
Output: 888
💡 Note: To maximize: first digit is 9, second digit is 0 (not 9), so replace 0→9 to get 991. To minimize: first digit 9≠1, so replace 9→1 to get 101. Difference: 991 - 101 = 890
Example 3 — Edge Case with 1
$ Input: num = 123
Output: 820
💡 Note: To maximize: first digit 1 (not 9), so replace 1→9 to get 923. To minimize: first digit 1≠1 is false, so find next non-0/1 digit which is 2, replace 2→0 to get 103. Difference: 923 - 103 = 820

Constraints

  • 1 ≤ num ≤ 108
  • num does not contain any leading zeros

Visualization

Tap to expand
Max Difference Strategy OverviewInput432MAXIMIZEStrategy: First non-9 → 9432 → 932MINIMIZEStrategy: First digit → 1432 → 132DIFFERENCE932 - 132 = 800💡 Leftmost digits have maximum impact on value
Understanding the Visualization
1
Input
Original number with specific digit pattern
2
Transform
Apply optimal digit replacement strategy
3
Output
Calculate maximum possible difference
Key Takeaway
🎯 Key Insight: The leftmost digit has the highest impact, so prioritize changing it for maximum effect
Asked in
Google 35 Microsoft 28 Amazon 22
32.0K Views
Medium Frequency
~15 min Avg. Time
856 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