Skip to content

Commit aa61036

Browse files
authored
Create maximum-swap.py
1 parent 8952c85 commit aa61036

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

Python/maximum-swap.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
# Time: O(l), l is the length of the number string
2+
# Space: O(l)
3+
4+
class Solution(object):
5+
def maximumSwap(self, num):
6+
"""
7+
:type num: int
8+
:rtype: int
9+
"""
10+
digits = list(str(num))
11+
left, right = 0, 0
12+
max_idx = len(digits)-1
13+
for i in reversed(xrange(len(digits))):
14+
if digits[i] > digits[max_idx]:
15+
max_idx = i
16+
elif digits[max_idx] > digits[i]:
17+
left, right = i, max_idx
18+
digits[left], digits[right] = digits[right], digits[left]
19+
return int("".join(digits))

0 commit comments

Comments
 (0)