[Geeks for Geeks] Largest number in K swaps

Largest number in K swaps

Given a number K and string str of digits denoting a positive integer, build the largest number possible by performing swap operations on the digits of str at most K times.

  • Time : O(n^2 * k!)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
//Function to find the largest number after k swaps.
string findMaximumNum(string& str, int k, int pos = 0) {
if(pos >= str.length() or k == 0) return str;
string res = str;
for(int i = pos + 1; i < str.length(); i++) {
if(str[i] > str[pos]) {
swap(str[i], str[pos]);
res = max(res, findMaximumNum(str, k - 1, pos + 1));
swap(str[i], str[pos]);
}
}

return max(res, findMaximumNum(str, k, pos + 1));
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/22/PS/GeeksforGeeks/largest-number-in-k-swaps/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.