Find Maximum number possible by doing at | C ++ 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 ; Return if no swaps left ; Consider every digit ; Compare it with all digits after it ; 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 ; swap str [ i ] with str [ j ] ; If current num is more than maximum so far ; recurse of the other k - 1 swaps ; Backtrack ; Driver code
#include <bits/stdc++.h> NEW_LINE 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 ; }