1529 Max Difference You Can Get From Changing An Integer
1529 Max Difference You Can Get From Changing An Integer
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:
1
2
3
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:
1
2
3
4
5
6
7
**Input:** num = 555
**Output:** 888
**Explanation:** The first time pick x = 5 and y = 9 and store the new integer in a.
The second time pick x = 5 and y = 1 and store the new integer in b.
We have now a = 999 and b = 111 and max difference = 888
Example 2:
1
2
3
4
5
6
7
**Input:** num = 9
**Output:** 8
**Explanation:** The first time pick x = 9 and y = 9 and store the new integer in a.
The second time pick x = 9 and y = 1 and store the new integer in b.
We have now a = 9 and b = 1 and max difference = 8
Constraints:
1
1 <= num <= 108
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class Solution:
def maxDiff(self, num: int) -> int:
l = list(str(num))
first = 0
last = 0
for index,k in enumerate(l):
if k != '9':
first = index
break
for index,k in enumerate(l):
if k != '1' and k != '0':
last = index
break
high = []
low = []
for index, k in enumerate(l):
if k == l[first]:
high.append('9')
else:
high.append(k)
for index, k in enumerate(l):
if k == l[last]:
if last != 0:
low.append('0')
else:
low.append('1')
else:
low.append(k)
return int("".join(high)) - int("".join(low))
This post is licensed under CC BY 4.0 by the author.