3-5 lines, Python/C++/Java/Ruby

  • 3


    def maximumSwap(self, num):
        places = [10**i for i in range(len(str(num)))]
        return max(num + num/p%10*(q-p) + num/q%10*(p-q)
                   for p in places for q in places)


    int maximumSwap(int num) {
        int maxi = 0;
        for (int p=1; p<=num; p*=10)
            for (int q=p; q<=num; q*=10)
                maxi = max(maxi, num + num/p%10*(q-p) + num/q%10*(p-q));
        return maxi;


    public int maximumSwap(int num) {
        int max = 0;
        for (int p=1; p<=num; p*=10)
            for (int q=p; q<=num; q*=10)
                max = Math.max(max, num + num/p%10*(q-p) + num/q%10*(p-q));
        return max;


    def maximum_swap(num)
        .times.map { |i| 10**i }.repeated_combination(2)
        .map { |p, q| num + num/p%10*(q-p) + num/q%10*(p-q) }

    There are so very few possibilities that I just try them all, swapping between any two places p and q (where places are 1, 10, 100, 1000, etc, i.e., the "ones place", "tens place", "hundreds place", etc). With num/p%10 I get the digit at place p, and multiplying it with (q-p) takes it out of place p and puts it into place q. And move the digit from place q to place p the same way.

Log in to reply

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