Failing for larger test cases : Solved


#1

The answer to the question is itself in these three test cases:
1714254313 ,5 --> 7544331211
271425431 , 3 --> 754422131
7599 ,2 --> 9975
Hopefully, this will help you out to find the missing logic.
Hint: Don’t be greedy, be recursive :grinning:


#2

From these 3 test cases, I got where i was wrong but I am still not able to find the missing logic. Please send the correct code.


#3

Basically you need to try all the possible swaps.
like in 7599
7 can be swapped with index 2,3 so first you need to try swapping with index 2 and proceed then again come back and try swapping with index 3

void solver (string A, int B, string &Ans){
if(B<=0)return ;

for(int i=0;i<A.size();i++)
    
    for(int j=i+1;j<A.size();j++)
        if(A[j]>A[i]){
            //swapping
            char t=A[j];
            A[j] = A[i];
            A[i] = t;
            
            if(Ans < A)
                Ans = A;
            solver(A, B-1, Ans);
            //re swap
            A[i] = A[j];
            A[j] = t;
        }
  }