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: 890
💡 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 You Can Get From Changing an Integer INPUT 5 5 5 num = 555 All digits are the same: 5 We need to find two numbers a (max) and b (min) GOAL Maximize: a - b a = Replace to get MAX b = Replace to get MIN ALGORITHM STEPS 1 Find MAX (a) Replace first non-9 with 9 555 --> Replace 5 with 9 a = 999 2 Find MIN (b) Replace first digit carefully 555 --> Replace 5 with 1 b = 111 3 Calculate Difference result = a - b 999 - 111 = 888 4 Return Result Max difference found FINAL RESULT Maximum Difference 888 BREAKDOWN a (max): 999 b (min): 111 Difference: 888 OK - Valid Result No leading zeros, not 0 Key Insight: Greedy Approach To maximize 'a': Find the leftmost digit that is not 9, replace all its occurrences with 9. To minimize 'b': If first digit is not 1, replace it with 1. Otherwise, find first digit > 0 (not first) and replace with 0. This greedy strategy ensures maximum difference while avoiding leading zeros. TutorialsPoint - Max Difference You Can Get From Changing an Integer | Greedy Approach
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