Python, single pass with DP


  • 0
    B
    class Solution(object):
        def maximumSwap(self, num):
            """
            :type num: int
            :rtype: int
            """
            best = num
            n = len(str(num))
            j, second = 0, num%10
            for i in range(1, n):
                first = (num%10**(i+1))/10**i
                new = num-first*10**i-second*10**j+first*10**j+second*10**i
                best = max(best, new)
                if first > second:
                    j, second = i, first
            return best
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.