Mid/SeniorGreedyMath

Max Difference You Can Get From Changing an Integer

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 max difference between a and b.

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

Example 1
Inputnum = 555
Output888
Changing all 5s to 9 gives a = 999, and changing all 5s to 1 gives b = 111, so the max difference is 888.
Example 2
Inputnum = 9
Output8
Changing 9 to 9 gives a = 9, and changing 9 to 1 gives b = 1, so the max difference is 8.

Constraints

  • 1 <= num <= 10^8

Asked at 6 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate