Simple, easy C++ solution using Backtracking


#1

`string ans;
void Max_str(string A,int B,int index)
{
if(B==0) return;

    for(int i=index;i<A.size();i++)
    {
        for(int j=i;j<A.size();j++)
        {
            swap(A[i],A[j]);
            if(A>=ans) ans=A;
            Max_str(A,B-1,index+1);
            swap(A[i],A[j]);
        }
    }
}


string Solution::solve(string A, int B) {
    ans=A;
    Max_str(A,B,0);
    return ans;
    
}`

#2

one loop should be sufficient right? why Two loops.


#3

Maybe one loop would be sufficient but as a interview perspective, we should always start with brute force approach then proceed to next efficient solution, in this case, it worked so i left it there. But there might be efficient solution then this one.