Maximum Swap — LeetCode 670 Python Solution
MediumGreedyMath
- Problem
- #670
- Pattern
- Greedy
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are given an integer num. You can swap two digits at most once to get the maximum valued number.
Example
- Input
- num = 2736
- Output
- 7236
- Explanation
- Swap the number 2 and the number 7.
Python solution
Python
class Solution:
def maximumSwap(self, num: int) -> int:
s = list(str(num))
n = len(s)
d = list(range(n))
for i in range(n - 2, -1, -1):
if s[i] <= s[d[i + 1]]:
d[i] = d[i + 1]
for i, j in enumerate(d):
if s[i] < s[j]:
s[i], s[j] = s[j], s[i]
break
return int(''.join(s))Complexity
| Measure | Complexity |
|---|---|
| Time | O(\log M) |
| Space | O(\log M) auxiliary |
Pattern: Greedy
Take the locally best option every time — when you can prove that never costs you later. LeetCode 670. Maximum Swap is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.
The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 670. Maximum Swap?
- LeetCode 670. Maximum Swap is rated Medium on LeetCode.
- What is the time complexity of LeetCode 670. Maximum Swap?
- The Python solution on this page runs in O(\log M).
- What is the space complexity of LeetCode 670. Maximum Swap?
- The Python solution on this page uses O(\log M) auxiliary space.
- What topics does LeetCode 670. Maximum Swap cover?
- LeetCode 670. Maximum Swap is tagged Greedy and Math on LeetCode.