Maximum Swap

Problem Id: 670 Difficulty: Medium


Intuition

Solution


class Solution:
    def maximumSwap(self, num: int) -> int:
        if num <= 9:
            return num
        ans = num

        num = list(str(num))
        for i in range(len(num)):
            for j in range(i + 1, len(num)):
                num[i], num[j] = num[j], num[i]
                ans = max(ans, int(''.join(num)))
                num[i], num[j] = num[j], num[i]
        return ans