Maximum Swap in Python

PythonServer Side ProgrammingProgramming

Suppose we have a non-negative integer; we could swap two digits at most once to get the maximum valued number. We have to return the maximum valued number we can get. So if the input is like 2736 then the output will be 7236. So here we are swapping 2 and 7.

To solve this, we will follow these steps −

  • num := cut each digit from the number, and make a list
  • num1 := sort the num in reverse order
  • index := 0
  • while index < length of num
    • if num1[index] is not same as num[index]
      • a := subarray of num from index (index + 1) to end
      • reverse a
      • a := length of a – index of num[index] of a + index + 1 – 1
      • num[index], num[a] := num[a], num[index]
      • break the loop
    • increase index by 1
  • join the numbers present in num and make this as integer
  • return the result.

Example(Python)

Let us see the following implementation to get a better understanding −

 Live Demo

class Solution:
   def maximumSwap(self, num):
      num = list(map(int,list(str(num))))
      num1 = sorted(num,reverse=True)
      index=0
      while index<len(num):
         if num1[index]!=num[index]:
            a = num[index+1:]
            a.reverse()
            a=len(a) - a.index(num1[index])+index+1 -1
            num[index],num[a] = num[a],num[index]
            break
         index+=1
      return int("".join(str(x) for x in num))
ob1 = Solution()
print(ob1.maximumSwap(5397))

Input

5397

Output

9357
raja
Published on 27-Feb-2020 14:59:28
Advertisements