maximum swap

🏠

Credit: awice

 1 class Solution:
 2     def maximumSwap(self, num):
 3         A = [*map(int, str(num))]
 4         last = {x: i for i, x in enumerate(A)}
 5         for i, x in enumerate(A):
 6             for d in range(9, x, -1):
 7                 if last.get(d, 0) > i:
 8                     A[i], A[last[d]] = A[last[d]], A[i]
 9                     return int("".join(map(str, A)))
10         return num
11 
12 
13 s = Solution()
14 m = s.maximumSwap
15 
16 assert m(675442) == 765442
17 assert m(109132) == 901132
18 assert m(650931) == 950631
19 assert m(546596) == 946556