forked from derekhh/HackerRank
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbigger-is-greater.cpp
More file actions
42 lines (40 loc) · 803 Bytes
/
bigger-is-greater.cpp
File metadata and controls
42 lines (40 loc) · 803 Bytes
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
/*
bigger-is-greater.cpp
Bigger is Greater
*/
#include <algorithm>
#include <iostream>
#include <string>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
string s;
cin >> s;
int pos = -1;
for (int i = s.size() - 1; i > 0; i--) {
if (s[i] > s[i - 1]) {
pos = i;
break;
}
}
if (pos == -1) {
cout << "no answer" << endl;
} else {
int minVal = 1000, maxIdx = -1;
for (int i = pos; i < s.size(); i++) {
if (s[i] > s[pos - 1]) {
if (s[i] < minVal || (s[i] == minVal && i > maxIdx)) {
minVal = s[i];
maxIdx = i;
}
}
}
swap(s[pos - 1], s[maxIdx]);
reverse(s.begin() + pos, s.end());
cout << s << endl;
}
}
return 0;
}