Skip to content

Commit 677aa8b

Browse files
committed
added Maximum Swap (medium)
1 parent 74ef3c0 commit 677aa8b

File tree

3 files changed

+51
-0
lines changed

3 files changed

+51
-0
lines changed

Medium/MaximumSwap/README.md

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
2+
# Maximum Swap
3+
[Leetcode Link](https://leetcode.com/problems/maximum-swap/)
4+
5+
## Problem:
6+
7+
Given a non-negative integer, you could swap two digits **at most** once to get the maximum valued number. Return the maximum valued number you could get.
8+
9+
## Example:
10+
11+
```
12+
Input: 2736
13+
Output: 7236
14+
Explanation: Swap the number 2 and the number 7.
15+
```
16+
```
17+
Input: 9973
18+
Output: 9973
19+
Explanation: No swap.
20+
```
21+
22+
## Note:
23+
24+
- The given number is in the range [0, 108]

Medium/MaximumSwap/solution.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
class Solution:
2+
def maximumSwap(self, num: int) -> int:
3+
arr = list(str(num))
4+
# print(arr)
5+
for i, n in enumerate(arr):
6+
n = int(n)
7+
maxNum = max([int(num) for num in arr[i:]])
8+
if maxNum > n:
9+
for j in range(len(arr)-1, i-1, -1):
10+
if int(arr[j]) == maxNum:
11+
arr[i], arr[j] = arr[j], arr[i]
12+
# print(arr)
13+
return int("".join(arr))
14+
return int("".join(arr))
15+
16+
17+
18+
# test driver
19+
sol = Solution()
20+
num = 2736
21+
print("Input:", num)
22+
print("Output:", sol.maximumSwap(num))
23+
24+
num = 98368
25+
print("Input:", num)
26+
print("Output:", sol.maximumSwap(num))

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,7 @@ Languages used: Java and Python
7171
- [Predict the Winner](Medium/PredictWinner)
7272
- [Subarray Sum Equals K](Medium/SubarraySumEqualsK)
7373
- [Find Minimum in Rotated Sorted Array](Medium/FindMinInRotatedSortedArray)
74+
- [Maximum Swap](Medium/MaximumSwap)
7475
- Hard
7576
- [Maximum Score Words Formed by Letters](Hard/MaximumScoreWords)
7677
- [Reducing Dishes](Hard/ReducingDishes)

0 commit comments

Comments
 (0)