Description

You are given an integer num. You can swap two digits at most once to get the maximum valued number.

Return the maximum valued number you can get.

1
2
3
4
5
Example 1:

Input: num = 2736
Output: 7236
Explanation: Swap the number 2 and the number 7.
1
2
3
4
5
Example 2:

Input: num = 9973
Output: 9973
Explanation: No swap.
1
2
Constraints:
0 <= num <= 108

Approach

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
def maximumSwap(self, num: int) -> int:
result = num
num_list = list(str(num))
max_idx = -1

for i in range(len(num_list)-1,-1,-1):
if num_list[i] > num_list[max_idx]:
max_idx = i
else:
num_list[i], num_list[max_idx] = num_list[max_idx], num_list[i]
result = max(result,int("".join(num_list)))
num_list[i], num_list[max_idx] = num_list[max_idx], num_list[i]

return result

# Example usage:
num = 2736
solution = Solution()
print(f"The maximum valued number after at most one swap is: {solution.maximumSwap(num)}")