
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Maximum Swap in Python
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
- if num1[index] is not same as num[index]
- 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 −
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
- Related Articles
- Fair Candy Swap in Python
- Swap Consecutive Even Elements in Python
- Finding the maximum number using at most one swap in JavaScript
- Previous Permutation With One Swap in Python
- Pattern After Double, Reverse, and Swap in Python
- Program to swap string characters pairwise in Python
- Swap two variables in one line in using Python?
- Program to swap nodes in a linked list in Python
- How to remove swap files using Python?
- How to Swap Two Variables using Python?
- Python Pandas - Swap levels of a MultiIndex
- Swap Even Index Elements And Odd Index Elements in Python
- Program to minimize hamming distance after swap operations in Python
- Maximum Subarray in Python
- Python program to swap case of English word

Advertisements