[LeetCode] Maximum Swap

670. Maximum Swap

You are given an integer num. You can swap two digits at most once to get the maximum valued number.

Return the maximum valued number you can get.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public:
int maximumSwap(int num) {
string res = to_string(num);
int n = res.length();
unordered_map<char, int> mp;
for(int i = 0; i < n; i++)
mp[res[i]] = i;
for(int i = 0; i < n; i++) {
int pos = i;
char ma = res[i];
for(auto& [k, v] : mp) {
if(k <= ma or v <= i) continue;
ma = k;
pos = v;
}
if(pos != i) {
swap(res[i], res[pos]);
return stoi(res);
}
}

return num;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/05/PS/LeetCode/maximum-swap/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.