You are given a positive integer num. You build two new integers from it, a and b, each with one digit-replacement operation applied to the original num:
-
Pick a digit
x
(
0 <= x <= 9
).
-
Pick a digit
y
(
0 <= y <= 9
).
y
may equal
x
.
-
Replace every occurrence of
x
in the decimal representation of
num
with
y
.
The resulting integer cannot have a leading zero and cannot be 0. Return the largest possible value of a - b.
Function Signature
def max_diff(num: int) -> int:
Rules
-
Both operations start from the original
num
. The second operation is not applied to
a
.
-
The two operations may pick different
x
and
y
.
-
Choosing
y = x
, or an
x
that does not appear in
num
, leaves the number unchanged. That still counts as a valid operation.
-
A replacement that would put a 0 in the leading position is not allowed.
Constraints
Examples
Input: num = 555
Output: 888
Replacing 5 with 9 gives a = 999, and replacing 5 with 1 gives b = 111, so the answer is 999 - 111 = 888. Replacing 5 with 0 is not allowed because it would produce 0.
Input: num = 9
Output: 8
Keeping the number as it is gives a = 9, and replacing 9 with 1 gives b = 1, so the difference is 8.
Input: num = 123456
Output: 820000
Replacing 1 with 9 gives a = 923456. For b, the leading 1 cannot drop to 0, so the best move is to replace 2 with 0, which gives b = 103456. The difference is 923456 - 103456 = 820000.