Largest number in K swaps | Practice | GeeksforGeeks

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.

Example 1:
Input:
K = 4
str = "1234567"
Output:
7654321
Explanation:
Three swaps can make the
input 1234567 to 7654321, swapping 1
with 7, 2 with 6 and finally 3 with 5

Example 2:
Input:
K = 3
str = "3435335"
Output:
5543333
Explanation:
Three swaps can make the input
3435335 to 5543333, swapping 3 
with 5, 4 with 5 and finally 3 with 4 


Your task:
You don't have to read input or print anything. Your task is to complete the function findMaximumNum() which takes the string and an integer as input and returns a string containing the largest number formed by perfoming the swap operation at most k times.

Expected Time Complexity: O(n!/(n-k)!) , where n = length of input string
Expected Auxiliary Space: O(n)

Constraints:
1 ≤ |str| ≤ 30
1 ≤ K ≤ 10
+5
amitpurohit47471 week ago
class Solution
{
    public:
    void rec(string str, int k, int a, string &ans){
        ans=max(ans,str);
        if(k==0) return;
        for(int i=a;i<str.length()-1;i++){
            for(int j=i+1;j<str.length();j++){
                if(str[j]>str[i]){
                    swap(str[i],str[j]);
                    rec(str,k-1,i+1,ans);
                    swap(str[i],str[j]);
                }
            }
        }
    }
    
    string findMaximumNum(string str, int k)
    {
       // code here.
       string ans=str;
       rec(str,k,0,ans);
       return ans;
    }
};
0
joyrockok2 weeks ago
class Solution{static String strMax = "";public static String findMaximumNum(String str, int k) {      strMax = "";   char [] arr = str.toCharArray();         findNum(arr, k);      if(strMax.isEmpty()) return str;      return strMax;}public static void findNum(char [] arr, int k) {    if(k==0) return;      int size = arr.length;        for(int i=0; i<size-1; i++) {     for(int j=i+1; j<size; j++) {      char a = arr[i];      char b = arr[j];            if(a<b) {       char tmp = arr[i];       arr[i] = arr[j];       arr[j] = tmp;                     String toStr = String.valueOf(arr);              if(toStr.compareTo(strMax) > 0){        strMax = toStr;       }              findNum(arr, k-1);      }            if(a<b) {       char tmp = arr[i];       arr[i] = arr[j];       arr[j] = tmp;      }     }    }}}
0
vadapaav4 weeks ago
Whats wrong with this code ?? help ..
string findMaximumNum(string str, int k)
    {
        int n = str.length();
    	for(int i=0; i<n; i++) {
    	    if(k==0)
    	        break;
    	    int ind = i;
    	    for(int j=n-1; j>i; j--) {
    	        if(str[j]>str[ind])
    	            ind = j;
    	    }
    	    if(i!=ind) {
    	        k--;
    	        swap(str[ind], str[i]);
    	    }
    	}
    	return str;
    }
0
shraddhakumari5151 month ago
can someone tell me why my code is not working?
please help
 
class Solution{   //Function to find the largest number after k swaps.      public static String findMaximumNum(String str, int k)       {           //code here.           String[] a=new String[1];           a[0]="0";           int[] k1=new int[1];           k1[0]=k;           if(str.length()==1)           return str;               sol(0,str,k,a);        return a[0];       }              static void  sol(int st,String str, int k1,String[] a)       {          if(k1==0 || st==str.length())          {          return ;          }                              for(int i=st;i<str.length();i++)          {              if(Character.getNumericValue(str.charAt(i))<Character.getNumericValue(str.charAt(st)) && st!=i)              continue;                           str=swap(str,i,st);               if(Long.parseLong(str)>Long.parseLong(a[0]))            {            a[0]=copy(str);            }            if(i==st)            sol(st+1,str,k1,a);              sol(st+1,str,k1--,a);              str=swap(str,i,st);              }             return;           }                            static String swap(String str, int i, int j)   {       char ch[] = str.toCharArray();       char temp = ch[i];       ch[i] = ch[j];       ch[j] = temp;       return String.valueOf(ch);   }   static String copy(String str)   {       String z=str;       return z;   }}               
+6
vinamrajha1 month ago
void helper(string str, string &maxi, int k, int idx){
       if(k==0) return;
       char c = str[idx];
       for(int i = idx+1; i<str.length(); ++i){
           if(str[i]>c) c = str[i];
       }
       if(c != str[idx]) k--;
       for(int i =0; i<str.length(); i++){
           if(str[i]==c){
               swap(str[idx], str[i]);
               if(maxi < str) maxi = str;
               helper(str, maxi, k, idx+1);
               swap(str[idx], str[i]);
           }
       }
   }
   string findMaximumNum(string str, int k)
   {
      // code here.
      string maxi = str;
      helper(str, maxi, k, 0);
      return maxi;
   }
0
blank551k2 months ago
class Solution
{
   public:
   string s;
   void answer(string curr,int k,int i){
       if(k==0 || i==s.size()){
           if(s<curr){
               s=curr;
           }
           return;
       }
       
       for(int j=i;j<curr.size();++j){
           if(curr[j]<=curr[i] && i!=j){
               continue;
           }
           
           swap(curr[j],curr[i]);
           // saving the swap when i=j;
           if(i==j){
               answer(curr,k,i+1);
           }
           answer(curr,k-1,i+1);
           swap(curr[j],curr[i]);
       }
       return ;
       
   }
   //Function to find the largest number after k swaps.
   string findMaximumNum(string str, int k)
   {
      s=str;
      answer(str,k,0);
      return s;
   }
};

0
naveenkushawaha20032 months ago
//0.0 sec Very Simple Solution........
class Solution{   public:   //Function to find the largest number after k swaps.   string find(int i,string str,int k,int t){if(i>=str.size()||t==k) return str;string str1,str2=str;stack<pair<char,int>>s;char ch=str[i];for(int j=i+1;j<str.size();j++){           if(ch<=str[j]){            //cout<<ch<<" "<<str[j]<<endl;            while(!s.empty()&&str[j]>s.top().first)             s.pop();                s.push(make_pair(str[j],j));               ch=str[j];           }}if(s.empty()==true){ str1=find(i+1,str,k,t);       if(str2<str1)        str2=str1;}while(!s.empty()){ if(str[i]==s.top().first)  str1=find(i+1,str,k,t); else{ swap(str[i],str[s.top().second]); str1=find(i+1,str,k,t+1); swap(str[i],str[s.top().second]);} if(str2<str1) str2=str1;  s.pop();}return str2;   }   string findMaximumNum(string str, int k)   {     return find(0,str,k,0);    }
+1
thotakurapavan3 months ago
java solution  ::
 
class Solution{   //Function to find the largest number after k swaps.   public static String findMaximumNum(String str, int k)   {       char[] vals = str.toCharArray();       return findmax(vals, 0 , k);   }
   public static String findmax(char[] vals, int start, int k) {       if(0 == k) return String.valueOf(vals);       if(start == vals.length) return String.valueOf(vals);
       char maxVal = vals[start];              for(int i = start+1; i<vals.length; i++) {           if(maxVal < vals[i]) {               maxVal = vals[i];           }       }              if(vals[start] == maxVal) {           return findmax(vals, start+1, k);       }              String max = String.valueOf(vals);              for(int i = start+1; i<vals.length; i++) {           if(Integer.valueOf(maxVal) == Integer.valueOf(vals[i])) {               char[] newVal = vals.clone();               char temp = newVal[start];               newVal[start] = newVal[i];               newVal[i] = temp;               String newMax = findmax(newVal, start+1, k-1);               if(max.compareTo(newMax) < 0) {                  max = newMax;               }           }       }              return max;   }}
-1
2019011223 months ago
Why the solution does not get accepted in C++, and shows abort 3 (SIGABRT) error after test case 4 ?
0
araj2920183 months ago
class Solution{   public:   //Function to find the largest number after k swaps.   void klp(string str,int k,string &maxm,int ctr){       if(k==0){           return ;       }       int n=str.size();       char maxi=str[ctr];       for(int i=ctr+1;i<n;i++){           if(str[i]>maxi){               maxi=str[i];           }       }       if(maxi!=str[ctr]){           k--;       }       for (int j=n-1;j>=ctr;j--){           if(str[j]==maxi){               swap(str[ctr],str[j]);               if(str.compare(maxm)>0){                   maxm=str;               }               klp(str,k,maxm,ctr+1);               swap(str[ctr],str[j]);           }       }   }   string findMaximumNum(string str, int k)   {      string maxm="";      klp(str,k,maxm,0);      return maxm;   }};
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.