-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathMaximumSwap.cpp
71 lines (58 loc) · 1.65 KB
/
MaximumSwap.cpp
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
class Solution {
public:
void makeMap(map<int, vector<int> >& m, string s){
int i = 0, n = s.size();
while(i < n){
m[s[i]-'0'].push_back(i);
i++;
}
}
void swap(char& a, char& b){
char temp = a;
a = b;
b = temp;
}
bool findLarger(map<int, vector<int> >& m, int curr_index, int curr, int& index){
int num = 9;
while(curr < num){
if(m.find(num) != m.end()){
for(int i = m[num].size()-1; i >= 0; i--){
if(m[num][i] > curr_index){
index = m[num][i];
return true;
}
}
}
num--;
}
return false;
}
void printMap(map<int, vector<int> >& m){
map<int, vector<int> > :: iterator it = m.begin();
while(it != m.end()){
cout << it->first << " -> ";
for(int i = 0; i < (it->second).size(); i++){
cout << (it->second)[i] << ",";
}
cout << endl;
it++;
}
}
int maximumSwap(int num) {
string s = to_string(num);
map<int, vector<int> > m;
makeMap(m, s);
// printMap(m);
int i = 0, n = s.size();
while(i < n){
int index = -1;
if(findLarger(m, i, s[i]-'0', index)){
swap(s[i], s[index]);
break;
}
i++;
}
// cout << "ans " << s << endl;
return stoi(s);
}
};