670. Maximum Swap
[Medium] “Given a non-negative integer, return the maximum valued number you could get by swapping two digits once."
Python3:
class Solution:
def maximumSwap(self, num: int) -> int:
digits = list(map(int, str(num)))
for i in range(len(digits)):
if not digits[(i + 1):]:
break
else:
max_digit = max(digits[(i + 1):])
if max_digit > digits[i]:
# swap
curr = digits[i]
max_last_ind = max([j for (j, n) in enumerate(digits[(i + 1):]) if n == max_digit]) + i + 1
digits[i] = max_digit
digits[max_last_ind] = curr
return int("".join(map(str, digits)))
return num