Find Maximum number possible by doing at-most K swaps
Given two positive integers M and K, find the maximum integer possible by doing at-most K swap operations on its digits.
Examples:
Input: M = 254, K = 1
Output: 524
Explanation: Swap 5 with 2 so number becomes 524
Input: M = 254, K = 2
Output: 542
Explanation: Swap 5 with 2 so number becomes 524, Swap 4 with 2 so number becomes 542
Input: M = 68543, K = 1
Output: 86543
Explanation: Swap 8 with 6 so number becomes 86543
Input: M = 7599, K = 2
Output: 9975
Explanation: Swap 9 with 5 so number becomes 7995, Swap 9 with 7 so number becomes 9975
Input: M = 76543, K = 1
Output: 76543
Explanation: No swap is required.
Input: M = 129814999, K = 4
Output: 999984211
Explanation: Swap 9 with 1 so number becomes 929814991, Swap 9 with 2 so number becomes 999814291, Swap 9 with 8 so number becomes 999914281, Swap 1 with 8 so number becomes 999984211
Naive solution for the Largest number in K swaps:
The idea is to consider every digit and swap it with digits following it one at a time and see if it leads to the maximum number. The process is repeated K times. The code can be further optimized, if the current digit is swapped with a digit less than the following digit.
Follow the below steps to Implement the idea:
- Create a global variable that will store the maximum string or number.
- Define a recursive function that takes the string as a number and value of k
- Run a nested loop, the outer loop from 0 to the length of string -1, and the inner loop from i+1 to the end of the string.
- Swap the ith and jth characters and check if the string is now maximum and update the maximum string.
- Call the function recursively with parameters: string and k-1.
- Now again swap back the ith and jth character.
Below is the Implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void findMaximumNum(
string str, int k, string& max)
{
if (k == 0)
return ;
int n = str.length();
for ( int i = 0; i < n - 1; i++) {
for ( int j = i + 1; j < n; j++) {
if (str[i] < str[j]) {
swap(str[i], str[j]);
if (str.compare(max) > 0)
max = str;
findMaximumNum(str, k - 1, max);
swap(str[i], str[j]);
}
}
}
}
int main()
{
string str = "129814999" ;
int k = 4;
string max = str;
findMaximumNum(str, k, max);
cout << max << endl;
return 0;
}
|
Java
import java.util.*;
class GFG{
static String max;
static void findMaximumNum( char [] str,
int k)
{
if (k == 0 )
return ;
int n = str.length;
for ( int i = 0 ; i < n - 1 ; i++)
{
for ( int j = i + 1 ; j < n; j++)
{
if (str[i] < str[j])
{
char t = str[i];
str[i] = str[j];
str[j] = t;
if (String.valueOf(str).compareTo(max) > 0 )
max = String.valueOf(str);
findMaximumNum(str, k - 1 );
char c = str[i];
str[i] = str[j];
str[j] = c;
}
}
}
}
public static void main(String[] args)
{
String str = "129814999" ;
int k = 4 ;
max = str;
findMaximumNum(str.toCharArray(), k);
System.out.print(max + "\n" );
}
}
|
Python3
def swap(string, i, j):
return (string[:i] + string[j] +
string[i + 1 :j] +
string[i] + string[j + 1 :])
def findMaximumNum(string, k, maxm):
if k = = 0 :
return
n = len (string)
for i in range (n - 1 ):
for j in range (i + 1 , n):
if string[i] < string[j]:
string = swap(string, i, j)
if string > maxm[ 0 ]:
maxm[ 0 ] = string
findMaximumNum(string, k - 1 , maxm)
string = swap(string, i, j)
if __name__ = = "__main__" :
string = "129814999"
k = 4
maxm = [string]
findMaximumNum(string, k, maxm)
print (maxm[ 0 ])
|
C#
using System;
class GFG{
static String max;
static void findMaximumNum( char [] str,
int k)
{
if (k == 0)
return ;
int n = str.Length;
for ( int i = 0; i < n - 1; i++)
{
for ( int j = i + 1; j < n; j++)
{
if (str[i] < str[j])
{
char t = str[i];
str[i] = str[j];
str[j] = t;
if (String.Join( "" , str).CompareTo(max) > 0)
max = String.Join( "" , str);
findMaximumNum(str, k - 1);
char c = str[i];
str[i] = str[j];
str[j] = c;
}
}
}
}
public static void Main(String[] args)
{
String str = "129814999" ;
int k = 4;
max = str;
findMaximumNum(str.ToCharArray(), k);
Console.Write(max + "\n" );
}
}
|
Javascript
<script>
let max;
function findMaximumNum(str,k)
{
if (k == 0)
return ;
let n = str.length;
for (let i = 0; i < n - 1; i++)
{
for (let j = i + 1; j < n; j++)
{
if (str[i] < str[j])
{
let t = str[i];
str[i] = str[j];
str[j] = t;
if ((str).join( "" )>(max) )
max = (str).join( "" );
findMaximumNum(str, k - 1);
let c = str[i];
str[i] = str[j];
str[j] = c;
}
}
}
}
let str = "129814999" ;
let k = 4;
max = str;
findMaximumNum(str.split( "" ), k);
document.write(max + "<br>" );
</script>
|
Time Complexity: O((N2)k). For every digit, N2 recursive calls are generated until the value of k is 0 Thus O((N2)k).
Auxiliary Space: O(N). This is the space required to store the output string.
Find the Maximum number possible by doing at-most K swaps by swapping with the maximum element on the right:
It can be observed that to make the maximum string, the maximum digit is shifted to the front. So, instead of trying all pairs, try only those pairs where one of the elements is the maximum digit that is not yet swapped to the front.
Follow the below steps to Implement the idea::
- Create a global variable that will store the maximum string or number.
- Define a recursive function that takes the string as a number, the value of k, and the current index.
- Find the index of the maximum element in the range current index to end.
- if the index of the maximum element is not equal to the current index then decrement the value of k.
- Run a loop from the current index to the end of the array
- If the ith digit is equal to the maximum element
- Swap the ith and element at the current index and check if the string is now maximum and update the maximum string.
- Call the function recursively with parameters: string and k.
- Now again swap back the ith and element at the current index.
Below is the Implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void findMaximumNum(
string str, int k,
string& max, int ctr)
{
if (k == 0)
return ;
int n = str.length();
char maxm = str[ctr];
for ( int j = ctr + 1; j < n; j++) {
if (maxm < str[j])
maxm = str[j];
}
if (maxm != str[ctr])
--k;
for ( int j = n-1; j >=ctr; j--) {
if (str[j] == maxm) {
swap(str[ctr], str[j]);
if (str.compare(max) > 0)
max = str;
findMaximumNum(str, k, max, ctr + 1);
swap(str[ctr], str[j]);
}
}
}
int main()
{
string str = "129814999" ;
int k = 4;
string max = str;
findMaximumNum(str, k, max, 0);
cout << max << endl;
return 0;
}
|
Java
import java.io.*;
class Res {
static String max = "" ;
}
class Solution {
public static void findMaximumNum( char ar[], int k,
Res r)
{
if (k == 0 )
return ;
int n = ar.length;
for ( int i = 0 ; i < n - 1 ; i++) {
for ( int j = i + 1 ; j < n; j++) {
if (ar[j] > ar[i]) {
char temp = ar[i];
ar[i] = ar[j];
ar[j] = temp;
String st = new String(ar);
if (r.max.compareTo(st) < 0 ) {
r.max = st;
}
findMaximumNum(ar, k - 1 , r);
temp = ar[i];
ar[i] = ar[j];
ar[j] = temp;
}
}
}
}
public static void main(String[] args)
{
String str = "129814999" ;
int k = 4 ;
Res r = new Res();
r.max = str;
findMaximumNum(str.toCharArray(), k, r);
System.out.println(r.max);
}
}
|
Python3
def findMaximumNum(string, k, maxm, ctr):
if k = = 0 :
return
n = len (string)
mx = string[ctr]
for i in range (ctr + 1 ,n):
if int (string[i]) > int (mx):
mx = string[i]
if (mx! = string[ctr]):
k = k - 1
for i in range (ctr,n):
if (string[i] = = mx):
string[ctr], string[i] = string[i], string[ctr]
new_str = "".join(string)
if int (new_str) > int (maxm[ 0 ]):
maxm[ 0 ] = new_str
findMaximumNum(string, k , maxm, ctr + 1 )
string[ctr], string[i] = string[i], string[ctr]
if __name__ = = "__main__" :
string = "129814999"
k = 4
maxm = [string]
string = [char for char in string]
findMaximumNum(string, k, maxm, 0 )
print (maxm[ 0 ])
|
C#
using System;
class Res {
public String max = "" ;
}
public class Solution {
static void findMaximumNum( char []ar, int k,
Res r)
{
if (k == 0)
return ;
int n = ar.Length;
for ( int i = 0; i < n - 1; i++)
{
for ( int j = i + 1; j < n; j++)
{
if (ar[j] > ar[i]) {
char temp = ar[i];
ar[i] = ar[j];
ar[j] = temp;
String st = new String(ar);
if (r.max.CompareTo(st) < 0) {
r.max = st;
}
findMaximumNum(ar, k - 1, r);
temp = ar[i];
ar[i] = ar[j];
ar[j] = temp;
}
}
}
}
public static void Main(String[] args)
{
String str = "129814999" ;
int k = 4;
Res r = new Res();
r.max = str;
findMaximumNum(str.ToCharArray(), k, r);
Console.WriteLine(r.max);
}
}
|
Javascript
function findMaximumNum(string, k, maxm, ctr) {
if (k == 0) {
return ;
}
const n = string.length;
let mx = string[ctr];
for (let i = ctr + 1; i < n; i++) {
if (parseInt(string[i]) > parseInt(mx)) {
mx = string[i];
}
}
if (mx != string[ctr]) {
k = k - 1;
}
for (let i = ctr; i < n; i++) {
if (string[i] == mx) {
[string[ctr], string[i]] = [string[i], string[ctr]];
const new_str = string.join( "" );
if (parseInt(new_str) > parseInt(maxm[0])) {
maxm[0] = new_str;
}
findMaximumNum(string, k, maxm, ctr + 1);
[string[ctr], string[i]] = [string[i], string[ctr]];
}
}
}
const string = "129814999" ;
const k = 4;
const maxm = [string];
const strArr = string.split( "" );
findMaximumNum(strArr, k, maxm, 0);
console.log(maxm[0]);
|
Time Complexity: O(Nk), For every recursive call N recursive calls are generated until the value of k is 0, Thus O((Nk).
Auxiliary Space: O(N). The space required to store the output string.
Exercise:
Last Updated :
20 Feb, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...