Leetcode 670 Solution
This article provides solution to leetcode question 670 (maximum-swap)
Access this page by simply typing in "lcs 670" in your browser address bar if you have bunnylol configured.
Leetcode Question Link
https://leetcode.com/problems/maximum-swap
Solution
class Solution:
def maximumSwap(self, num: int) -> int:
if num == 0:
return 0
a = []
while num:
a.append(num % 10)
num //= 10
a = list(reversed(a))
b = [None] * len(a)
for i in reversed(range(len(a))):
if i == len(a) - 1:
b[i] = (a[i], i)
else:
b[i] = max(b[i + 1], (a[i], i))
for i in range(len(a)):
j = b[i][1]
if j == i or a[i] == a[j]:
continue
a[i], a[j] = a[j], a[i]
break
return int("".join([str(v) for v in a]))