LeetCode 670: Maximum Swap

link

A swap cannot increase numbers like below:

We need an increasing pair. Those two numbers will be candidate for swap.

We can improve the right.

Given the improved right, now we can also improve the left.

Time: \mathcal{O}(\lg{n}), space: \mathcal{O}(\lg{n}).

class Solution:
    def maximumSwap(self, num: int) -> int:
        def to_digits(num: int) -> List[int]:
            digits = []
            while num > 0:
                digits.append( num%10 )
                num //= 10
            return digits[::-1]
        def to_num(digits: List[int]) -> int:
            n = 0
            for d in digits:
                n = 10*n + d
            return n
        
        digit_list = to_digits(num)
        i = 0
        while i < len(digit_list)-1:
            if digit_list[i] < digit_list[i+1]:
                break
            i += 1
        
        if i == len(digit_list)-1:
            return num

        # Found a candidate.
        best_left, best_right = i, i+1

        # Try improving right.
        i = best_right+1
        while i < len(digit_list):
            if digit_list[i] >= digit_list[best_right]:
                best_right = i
            i += 1
        
        # Given the best_right, try improving left.
        i = best_left-1
        while i >= 0:
            if digit_list[i] < digit_list[best_right]:
                best_left = i
            i -= 1

        
        digit_list[best_left], digit_list[best_right] = digit_list[best_right], digit_list[best_left]

        return to_num(digit_list)

Leave a comment