Skip to content

Commit b4440d3

Browse files
committed
Sync LeetCode submission Runtime - 0 ms (100.00%), Memory - 17.9 MB (6.74%)
1 parent decc029 commit b4440d3

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

0670-maximum-swap/README.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
<p>You are given an integer <code>num</code>. You can swap two digits at most once to get the maximum valued number.</p>
2+
3+
<p>Return <em>the maximum valued number you can get</em>.</p>
4+
5+
<p>&nbsp;</p>
6+
<p><strong class="example">Example 1:</strong></p>
7+
8+
<pre>
9+
<strong>Input:</strong> num = 2736
10+
<strong>Output:</strong> 7236
11+
<strong>Explanation:</strong> Swap the number 2 and the number 7.
12+
</pre>
13+
14+
<p><strong class="example">Example 2:</strong></p>
15+
16+
<pre>
17+
<strong>Input:</strong> num = 9973
18+
<strong>Output:</strong> 9973
19+
<strong>Explanation:</strong> No swap.
20+
</pre>
21+
22+
<p>&nbsp;</p>
23+
<p><strong>Constraints:</strong></p>
24+
25+
<ul>
26+
<li><code>0 &lt;= num &lt;= 10<sup>8</sup></code></li>
27+
</ul>

0670-maximum-swap/solution.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# Time: O(n)
2+
# Space: O(n)
3+
4+
"""
5+
Algorithm:
6+
1. Convert the input number to a list of digits for easier manipulation.
7+
2. Create a dictionary that stores the last position of each digit in the number.
8+
3. For each position from left to right:
9+
a. Look for a larger digit (from 9 down to current digit) that appears later in the number
10+
b. If found, swap these digits and return the result
11+
4. If no swap is needed (number is already maximum), return the original number.
12+
"""
13+
14+
class Solution:
15+
def maximumSwap(self, num: int) -> int:
16+
digits = list(str(num))
17+
n = len(digits)
18+
19+
last_pos = {int(digit) : i for i, digit in enumerate(digits)}
20+
21+
for i in range(n):
22+
current_digit = int(digits[i])
23+
24+
for d in range(9, current_digit, -1):
25+
if d in last_pos and last_pos[d] > i:
26+
digits[i], digits[last_pos[d]] = digits[last_pos[d]], digits[i]
27+
return int(''.join(digits))
28+
29+
return num
30+
31+

0 commit comments

Comments
 (0)