Problem
You are given an integernum. You can swap two digits at most once to get the maximum valued number.
Return the maximum valued number you can get.
Examples
Constraints
- 0 <= num <= 10^8
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Tested Python solution for LeetCode 670 with 18 pytest cases. Generate a practice environment with lcpy.
lcpy gen -n 670 # by problem number
lcpy gen -s maximum_swap # by problem name
num. You can swap two digits at most once to get the maximum valued number.
Return the maximum valued number you can get.
Input: num = 2736
Output: 7236
Explanation: Swap the number 2 and the number 7.
Input: num = 9973
Output: 9973
Explanation: No swap.
class Solution:
# Time: O(d) where d is the number of digits
# Space: O(d)
def maximum_swap(self, num: int) -> int:
digits = list(str(num))
last: dict[int, int] = {int(d): i for i, d in enumerate(digits)}
for i, d in enumerate(digits):
for bigger in range(9, int(d), -1):
if bigger in last and last[bigger] > i:
j = last[bigger]
digits[i], digits[j] = digits[j], digits[i]
return int("".join(digits))
return num
| Time | Space |
|---|---|
| O(d) where d is the number of digits | O(d) |