Open In App

Find Maximum number possible by doing at-most K swaps

Last Updated : 17 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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++
// C++ program to find maximum
// integer possible by doing
// at-most K swap operations
// on its digits.
#include <bits/stdc++.h>
using namespace std;

// Function to find maximum
// integer possible by
// doing at-most K swap
// operations on its digits
void findMaximumNum(
    string str, int k, string& max)
{
    // Return if no swaps left
    if (k == 0)
        return;

    int n = str.length();

    // Consider every digit
    for (int i = 0; i < n - 1; i++) {

        // Compare it with all digits after it
        for (int j = i + 1; j < n; j++) {
            // if digit at position i
            // is less than digit
            // at position j, swap it
            // and check for maximum
            // number so far and recurse
            // for remaining swaps
            if (str[i] < str[j]) {
                // swap str[i] with str[j]
                swap(str[i], str[j]);

                // If current num is more
                // than maximum so far
                if (str.compare(max) > 0)
                    max = str;

                // recurse of the other k - 1 swaps
                findMaximumNum(str, k - 1, max);

                // Backtrack
                swap(str[i], str[j]);
            }
        }
    }
}

// Driver code
int main()
{
    string str = "129814999";

    int k = 4;

    string max = str;
    findMaximumNum(str, k, max);

    cout << max << endl;

    return 0;
}
Java
// Java program to find maximum
// integer possible by doing
// at-most K swap operations
// on its digits.
import java.util.*;
class GFG{
  
static String max;
// Function to find maximum
// integer possible by
// doing at-most K swap
// operations on its digits
static void findMaximumNum(char[] str, 
                           int k)
{
  // Return if no swaps left
  if (k == 0)
    return;

  int n = str.length;

  // Consider every digit
  for (int i = 0; i < n - 1; i++)
  {
    // Compare it with all digits
    // after it
    for (int j = i + 1; j < n; j++) 
    {
      // if digit at position i
      // is less than digit
      // at position j, swap it
      // and check for maximum
      // number so far and recurse
      // for remaining swaps
      if (str[i] < str[j])
      {
        // swap str[i] with 
        // str[j]
        char t = str[i];
        str[i] = str[j];
        str[j] = t;

        // If current num is more
        // than maximum so far
        if (String.valueOf(str).compareTo(max) > 0)
          max = String.valueOf(str);

        // recurse of the other 
        // k - 1 swaps
        findMaximumNum(str, k - 1);

        // Backtrack
        char c = str[i];
        str[i] = str[j];
        str[j] = c;
      }
    }
  }
}

// Driver code
public static void main(String[] args)
{
  String str = "129814999";
  int k = 4;
  max = str;
  findMaximumNum(str.toCharArray(), k);
  System.out.print(max + "\n");
}
}

// This code is contributed by 29AjayKumar 
Python3
# Python3 program to find maximum 
# integer possible by doing at-most
# K swap operations on its digits.

# utility function to swap two
# characters of a string
def swap(string, i, j):

    return (string[:i] + string[j] + 
            string[i + 1:j] + 
            string[i] + string[j + 1:])

# function to find maximum integer 
# possible by doing at-most K swap 
# operations on its digits
def findMaximumNum(string, k, maxm):
    
    # return if no swaps left
    if k == 0:
        return

    n = len(string)

    # consider every digit
    for i in range(n - 1):

        # and compare it with all digits after it
        for j in range(i + 1, n):

            # if digit at position i is less than 
            # digit at position j, swap it and 
            # check for maximum number so far and
            # recurse for remaining swaps
            if string[i] < string[j]:

                # swap string[i] with string[j]
                string = swap(string, i, j)

                # If current num is more than
                # maximum so far
                if string > maxm[0]:
                    maxm[0] = string

                # recurse of the other k - 1 swaps
                findMaximumNum(string, k - 1, maxm)

                # backtrack
                string = swap(string, i, j)

# Driver Code
if __name__ == "__main__":
    string = "129814999"
    k = 4
    maxm = [string]
    findMaximumNum(string, k, maxm)
    print(maxm[0])

# This code is contributed 
# by vibhu4agarwal
C#
// C# program to find maximum
// integer possible by doing
// at-most K swap operations
// on its digits.
using System;
class GFG{
  
static String max;
// Function to find maximum
// integer possible by
// doing at-most K swap
// operations on its digits
static void findMaximumNum(char[] str, 
                           int k)
{
  // Return if no swaps left
  if (k == 0)
    return;

  int n = str.Length;

  // Consider every digit
  for (int i = 0; i < n - 1; i++)
  {
    // Compare it with all digits
    // after it
    for (int j = i + 1; j < n; j++) 
    {
      // if digit at position i
      // is less than digit
      // at position j, swap it
      // and check for maximum
      // number so far and recurse
      // for remaining swaps
      if (str[i] < str[j])
      {
        // swap str[i] with 
        // str[j]
        char t = str[i];
        str[i] = str[j];
        str[j] = t;

        // If current num is more
        // than maximum so far
        if (String.Join("", str).CompareTo(max) > 0)
          max = String.Join("", str);

        // recurse of the other 
        // k - 1 swaps
        findMaximumNum(str, k - 1);

        // Backtrack
        char c = str[i];
        str[i] = str[j];
        str[j] = c;
      }
    }
  }
}

// Driver code
public static void Main(String[] args)
{
  String str = "129814999";
  int k = 4;
  max = str;
  findMaximumNum(str.ToCharArray(), k);
  Console.Write(max + "\n");
}
}

// This code is contributed by gauravrajput1 
Javascript
<script>
// Javascript program to find maximum
// integer possible by doing
// at-most K swap operations
// on its digits.

let max;

// Function to find maximum
// integer possible by
// doing at-most K swap
// operations on its digits
function findMaximumNum(str,k)
{

    // Return if no swaps left
  if (k == 0)
    return;
 
  let n = str.length;
 
  // Consider every digit
  for (let i = 0; i < n - 1; i++)
  {
  
    // Compare it with all digits
    // after it
    for (let j = i + 1; j < n; j++)
    {
      // if digit at position i
      // is less than digit
      // at position j, swap it
      // and check for maximum
      // number so far and recurse
      // for remaining swaps
      if (str[i] < str[j])
      {
      
        // swap str[i] with
        // str[j]
        let t = str[i];
        str[i] = str[j];
        str[j] = t;
 
        // If current num is more
        // than maximum so far
        if ((str).join("")>(max) )
          max = (str).join("");
 
        // recurse of the other
        // k - 1 swaps
        findMaximumNum(str, k - 1);
 
        // Backtrack
        let c = str[i];
        str[i] = str[j];
        str[j] = c;
      }
    }
  }
}

// Driver code
let str = "129814999";
let k = 4;
max = str;
findMaximumNum(str.split(""), k);
document.write(max + "<br>");

// This code is contributed by unknown2108
</script>

Output
999984211

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:: 

  1. Create a global variable that will store the maximum string or number.
  2. Define a recursive function that takes the string as a number, the value of k, and the current index.
  3. Find the index of the maximum element in the range current index to end.
  4. if the index of the maximum element is not equal to the current index then decrement the value of k.
  5. Run a loop from the current index to the end of the array
  6. If the ith digit is equal to the maximum element
  7. Swap the ith and element at the current index and check if the string is now maximum and update the maximum string.
  8. Call the function recursively with parameters: string and k.
  9. Now again swap back the ith and element at the current index.

Below is the Implementation of the above approach:

C++
// C++ program to find maximum
// integer possible by doing
// at-most K swap operations on
// its digits.
#include <bits/stdc++.h>
using namespace std;

// Function to find maximum
// integer possible by
// doing at-most K swap operations
// on its digits
void findMaximumNum(
    string str, int k,
    string& max, int ctr)
{
    // return if no swaps left
    if (k == 0)
        return;

    int n = str.length();

    // Consider every digit after
    // the cur position
    char maxm = str[ctr];
    for (int j = ctr + 1; j < n; j++) {
        // Find maximum digit greater
        // than at ctr among rest
        if (maxm < str[j])
            maxm = str[j];
    }

    // If maxm is not equal to str[ctr],
    // decrement k
    if (maxm != str[ctr])
        --k;

    // search this maximum among the rest from behind 
    //first swap the last maximum digit if it occurs more than 1 time
   //example str= 1293498 and k=1 then max string is 9293418 instead of 9213498
    for (int j = n-1; j >=ctr; j--) {
        // If digit equals maxm swap
        // the digit with current
        // digit and recurse for the rest
        if (str[j] == maxm) {
            // swap str[ctr] with str[j]
            swap(str[ctr], str[j]);

            // If current num is more than
            // maximum so far
            if (str.compare(max) > 0)
                max = str;

            // recurse other swaps after cur
            findMaximumNum(str, k, max, ctr + 1);

            // Backtrack
            swap(str[ctr], str[j]);
        }
    }
}

// Driver code
int main()
{
    string str = "129814999";
    int k = 4;

    string max = str;
    findMaximumNum(str, k, max, 0);

    cout << max << endl;

    return 0;
}
Java
// Java program to find maximum
// integer possible by doing
// at-most K swap operations on
// its digits.

import java.io.*;
class Res {
    static String max = "";
}

class Solution {
    // Function to set highest possible digits at given
    // index.
    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 digit at position i is less than digit
                // at position j, we swap them and check for
                // maximum number so far.
                if (ar[j] > ar[i]) {
                    char temp = ar[i];
                    ar[i] = ar[j];
                    ar[j] = temp;

                    String st = new String(ar);

                    // if current number is more than
                    // maximum so far
                    if (r.max.compareTo(st) < 0) {
                        r.max = st;
                    }
                    // calling recursive function to set the
                    // next digit.
                    findMaximumNum(ar, k - 1, r);

                    // backtracking
                    temp = ar[i];
                    ar[i] = ar[j];
                    ar[j] = temp;
                }
            }
        }
    }

    // Function to find the largest number after k swaps.
    public static void main(String[] args)
    {
        String str = "129814999";
        int k = 4;
        Res r = new Res();
        r.max = str;
        findMaximumNum(str.toCharArray(), k, r);
        //Print the answer stored in res class
        System.out.println(r.max);
    }
}
Python3
# Python3 program to find maximum
# integer possible by doing at-most
# K swap operations on its digits.

# function to find maximum integer
# possible by doing at-most K swap
# operations on its digits
def findMaximumNum(string, k, maxm, ctr):
     
    # return if no swaps left
    if k == 0:
        return
 
    n = len(string)
    # Consider every digit after
    # the cur position
    mx = string[ctr]

    for i in range(ctr+1,n):
        # Find maximum digit greater
        # than at ctr among rest
        if int(string[i]) > int(mx):
            mx=string[i]
            
    # If maxm is not equal to str[ctr],
    # decrement k        
    if(mx!=string[ctr]):
        k=k-1
    
    # search this maximum among the rest from behind
    # first swap the last maximum digit if it occurs more than 1 time
    # example str= 1293498 and k=1 then max string is 9293418 instead of 9213498
    for i in range(ctr,n):
        # If digit equals maxm swap
        # the digit with current
        # digit and recurse for the rest
        if(string[i]==mx):
            # swap str[ctr] with str[j]
            string[ctr], string[i] = string[i], string[ctr]
            new_str = "".join(string)
            # If current num is more than
            # maximum so far
            if int(new_str) > int(maxm[0]):
                  maxm[0] = new_str
 
            # recurse of the other k - 1 swaps
            findMaximumNum(string, k , maxm, ctr+1)

            # backtrack
            string[ctr], string[i] = string[i], string[ctr]
 
# Driver Code
if __name__ == "__main__":
    string = "129814999"
    k = 4
    maxm = [string]
    string = [char for char in string]
    findMaximumNum(string, k, maxm, 0)
    print(maxm[0])
 
# This code is contributed Aarti_Rathi
C#
// C# program to find maximum
// integer possible by doing
// at-most K swap operations on
// its digits.
using System;

class Res {
  public String max = "";
}

public class Solution {
  // Function to set highest possible digits at given
  // index.
  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 digit at position i is less than digit
        // at position j, we swap them and check for
        // maximum number so far.
        if (ar[j] > ar[i]) {
          char temp = ar[i];
          ar[i] = ar[j];
          ar[j] = temp;

          String st = new String(ar);

          // if current number is more than
          // maximum so far
          if (r.max.CompareTo(st) < 0) {
            r.max = st;
          }
          
          // calling recursive function to set the
          // next digit.
          findMaximumNum(ar, k - 1, r);

          // backtracking
          temp = ar[i];
          ar[i] = ar[j];
          ar[j] = temp;
        }
      }
    }
  }

  // Function to find the largest number after k swaps.
  public static void Main(String[] args)
  {
    String str = "129814999";
    int k = 4;
    Res r = new Res();
    r.max = str;
    findMaximumNum(str.ToCharArray(), k, r);

    // Print the answer stored in res class
    Console.WriteLine(r.max);
  }
}

// This code is contributed by shikhasingrajput 
Javascript
function findMaximumNum(string, k, maxm, ctr) {
  // return if no swaps left
  if (k == 0) {
    return;
  }
  
  const n = string.length;
  // Consider every digit after
  // the cur position
  let mx = string[ctr];

  for (let i = ctr + 1; i < n; i++) {
    // Find maximum digit greater
    // than at ctr among rest
    if (parseInt(string[i]) > parseInt(mx)) {
      mx = string[i];
    }
  }
  
  // If maxm is not equal to str[ctr],
  // decrement k
  if (mx != string[ctr]) {
    k = k - 1;
  }

  // search this maximum among the rest from behind
  // first swap the last maximum digit if it occurs more than 1 time
  // example str= 1293498 and k=1 then max string is 9293418 instead of 9213498
  for (let i = ctr; i < n; i++) {
    // If digit equals maxm swap
    // the digit with current
    // digit and recurse for the rest
    if (string[i] == mx) {
      // swap str[ctr] with str[j]
      [string[ctr], string[i]] = [string[i], string[ctr]];
      const new_str = string.join("");
      // If current num is more than
      // maximum so far
      if (parseInt(new_str) > parseInt(maxm[0])) {
        maxm[0] = new_str;
      }
      // recurse of the other k - 1 swaps
      findMaximumNum(string, k, maxm, ctr + 1);

      // backtrack
      [string[ctr], string[i]] = [string[i], string[ctr]];
    }
  }
}

// Driver Code
const string = "129814999";
const k = 4;
const maxm = [string];
const strArr = string.split("");
findMaximumNum(strArr, k, maxm, 0);
console.log(maxm[0]);

Output
999984211

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:  


 



Previous Article
Next Article

Similar Reads

Minimum swaps to reach permuted array with at most 2 positions left swaps allowed
Given a permuted array of length N of first N natural numbers, we need to tell the minimum number of swaps required in the sorted array of first N natural number to reach given permuted array where a number can be swapped with at most 2 positions left to it. If it is not possible to reach permuted array by above swap condition then print not possib
14 min read
Maximum possible sub-array sum after at most X swaps
Given an array arr[] of N integers and an integer X, the task is to find the maximum possible sub-array sum after applying at most X swaps.Examples: Input: arr[] = {5, -1, 2, 3, 4, -2, 5}, X = 2 Output: 19 Swap (arr[0], arr[1]) and (arr[5], arr[6]). Now, the maximum sub-array sum will be (5 + 2 + 3 + 4 + 5) = 19Input: arr[] = {-2, -3, -1, -10}, X =
8 min read
Minimize the max of Array by doing at most K increment and decrement
Given a positive array arr[] of size N (2 ≤ N ≤ 105) and a positive integer K, the task is to minimize the maximum value of arr[] by performing at most K operations where in each operation, you can select any two distinct integers i and j (0 ≤ i, j &lt; N), then increase the value of arr[i] by 1 and decrease the value of arr[j] by 1. Example: Input
9 min read
Minimum possible value T such that at most D Partitions of the Array having at most sum T is possible
Given an array arr[] consisting of N integers and an integer D, the task is to find the least integer T such that the entire array can be partitioned into at most D subarrays from the given array with sum atmost T. Examples: Input: D = 5, arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} Output: 15 Explanation: If T = 15, then 5 subarrays {{1, 2, 3, 4, 5}, {
9 min read
Minimize the size of Array by doing maximum absorptions
Given an array A consisting of N integers and an integer K, the task is to minimize the length of array A, by applying absorptions any number of times, such that: Any element in A (A[i]) can absorb any other element in A (A[j]), if it is at least K times the other, i.e. A[i] &gt;= K*A[j].If an element X is absorbed by any other element Y, then Y is
10 min read
Find the resulting output array after doing given operations
Given an array integers[] of integers of size N. Find the resulting output array after doing some operations: If the (i-1)th element is positive and ith element is negative then :If the absolute of (i)th is greater than (i-t)th, remove all the contiguous positive elements from left having absolute value less than ith.If the absolute of (i)th is sma
11 min read
Find lexicographically smallest string in at most one swaps
Given a string str of length N. The task is to find out the lexicographically smallest string when at most only one swap is allowed. That is, two indices 1 &lt;= i, j &lt;= n can be chosen and swapped. This operation can be performed at most one time. Examples: Input: str = "string" Output: gtrins Explanation: Choose i=1, j=6, string becomes - gtri
14 min read
Lexicographical smallest number after at most K consecutive swaps
Given a number in form of string str and an integer K, the task is to find the smallest integer that can be formed after performing at most K consecutive swaps. The consecutive swaps mean at one swap the character at index i can be swapped with character at index i - 1 or i + 1. Examples: Input: str = "76921", K = 3Output: 27691Explanation:27691 is
15 min read
Maximum number formed from array with K number of adjacent swaps allowed
Given an array a[ ] and the number of adjacent swap operations allowed are K. The task is to find the max number that can be formed using these swap operations. Examples: Input : a[]={ 1, 2, 9, 8, 1, 4, 9, 9, 9 }, K = 4 Output : 9 8 1 2 1 4 9 9 9 After 1st swap a[ ] becomes 1 9 2 8 1 4 9 9 9 After 2nd swap a[ ] becomes 9 1 2 8 1 4 9 9 9 After 3rd s
9 min read
Maximize median after doing K addition operation on the Array
Given an array arr[] of N elements and an integer K, the task is to perform at most K operation on the array. In the one operation increment any element by one of the array. Find maximize median after doing K such operation. Example: Input: arr[] = {1, 3, 4, 5}, K = 3Output: 5Explanation: Here we add two in the second element and one in the third e
9 min read
Article Tags :
Practice Tags :