Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Maximum Swap in Python
The Maximum Swap problem asks us to find the maximum possible number by swapping at most two digits in a given non-negative integer. For example, given 2736, we can swap digits 2 and 7 to get 7236, which is the maximum possible value.
Algorithm Overview
The approach works by comparing the original number with its digits sorted in descending order. When we find the first position where they differ, we perform the optimal swap ?
- Convert the number into a list of digits
- Create a sorted version in descending order to find the target arrangement
- Find the first position where the original and sorted versions differ
- Locate the rightmost occurrence of the target digit for optimal swapping
- Perform the swap and return the result
Example
Let's implement the maximum swap algorithm ?
class Solution:
def maximumSwap(self, num):
# Convert number to list of digits
digits = list(map(int, list(str(num))))
# Create sorted version in descending order
sorted_digits = sorted(digits, reverse=True)
index = 0
while index < len(digits):
# Find first position where original differs from sorted
if sorted_digits[index] != digits[index]:
# Get remaining digits from current position
remaining = digits[index + 1:]
remaining.reverse() # Reverse to find rightmost occurrence
# Calculate position of rightmost occurrence of target digit
swap_pos = len(remaining) - remaining.index(sorted_digits[index]) + index + 1 - 1
# Perform the swap
digits[index], digits[swap_pos] = digits[swap_pos], digits[index]
break
index += 1
# Convert back to integer
return int("".join(str(x) for x in digits))
# Test the solution
solution = Solution()
print(solution.maximumSwap(5397))
print(solution.maximumSwap(2736))
print(solution.maximumSwap(9973))
9357 7236 9973
How It Works
For input 5397:
- Original digits: [5, 3, 9, 7]
- Sorted descending: [9, 7, 5, 3]
- First difference at index 0: 5 ? 9
- Find rightmost 9 in remaining digits [3, 9, 7] ? position 2
- Swap positions 0 and 2: [9, 3, 5, 7] ? 9357
Alternative Approach
Here's a more intuitive solution that tracks the last occurrence of each digit ?
def maximum_swap_simple(num):
digits = list(str(num))
# Record last occurrence of each digit
last_occurrence = {}
for i, digit in enumerate(digits):
last_occurrence[digit] = i
# Try to find a larger digit to swap with current position
for i in range(len(digits)):
# Check digits 9 down to current digit + 1
for larger_digit in range(9, int(digits[i]), -1):
larger_digit_str = str(larger_digit)
# If larger digit exists later in the number
if larger_digit_str in last_occurrence and last_occurrence[larger_digit_str] > i:
# Perform swap
swap_pos = last_occurrence[larger_digit_str]
digits[i], digits[swap_pos] = digits[swap_pos], digits[i]
return int(''.join(digits))
return num
# Test the alternative approach
print(maximum_swap_simple(5397))
print(maximum_swap_simple(2736))
print(maximum_swap_simple(1234))
9357 7236 4231
Conclusion
The maximum swap problem can be solved by finding the optimal position to swap digits for maximum value. The key insight is to swap the leftmost smaller digit with the rightmost larger digit to maximize the result.
