-
Notifications
You must be signed in to change notification settings - Fork 1
/
87-largest-number-in-k-swaps.cpp
76 lines (61 loc) · 1.39 KB
/
87-largest-number-in-k-swaps.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
72
73
74
75
76
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution
{
string max;
public:
void swap(string& str, int& i, int& j)
{
char c = str[i];
str[i] = str[j];
str[j] = c;
}
void helperMax(string str, int& n, int k, int index)
{
if(k == 0)
return;
char maxchar = str[index];
for(int j = index + 1; j < n; ++j)
{
if(maxchar < str[j])
maxchar = str[j];
}
if(maxchar != str[index])
k--;
for(int i = (n - 1); i >= index; --i)
{
if(str[i] == maxchar)
{
swap(str, i, index);
if(str > max)
max = str;
helperMax(str, n, k, index + 1);
swap(str, i, index);
}
}
}
//Function to find the largest number after k swaps.
string findMaximumNum(string str, int k)
{
max = str;
int n = str.size();
helperMax(str, n, k, 0);
return max;
}
};
// { Driver Code Starts.
int main()
{
int t, k;
string str;
cin >> t;
while (t--)
{
cin >> k >> str;
Solution ob;
cout<< ob.findMaximumNum(str, k) << endl;
}
return 0;
}
// } Driver Code Ends