670. Maximum Swap

You are given an integer num. You can swap two digits at most once to get the maximum valued number. Return the maximum valued number you can get.

def maximumSwap(self, num: int) -> int:
    s = list(str(num))
    
    m = -1
    idx = -1
    replace = None
    for i in range(len(s) - 1, -1, -1):
        if int(s[i]) > m:
            m = int(s[i])
            idx = i
        elif int(s[i]) < m:
            replace = i, idx
    
    if not replace:
        return num
    
    i, idx = replace
    s[i], s[idx] = s[idx], s[i]
    
    return int(''.join(s))