1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
| class Solution:
def maximumSwap(self, num: int) -> int:
# Convert number to list of digits
num_list = list(str(num))
n = len(num_list)
# Traverse the list of digits
for i in range(n - 1):
# Find the maximum digit on the right of the current digit
max_digit_right = max(num_list[i+1:])
# Check if a greater digit is found on the right
if max_digit_right > num_list[i]:
# Find the rightmost occurrence of the maximum digit
swap_idx = num_list[::-1].index(max_digit_right)
swap_idx = n - 1 - swap_idx
# Swap the current digit with the rightmost occurrence of the maximum digit
num_list[i], num_list[swap_idx] = num_list[swap_idx], num_list[i]
break
# Convert the list of digits back to an integer
return int(''.join(num_list))
|