Find Maximum number possible by doing at | Java 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
import java . util . * ; class GFG { static String max ; static void findMaximumNum ( char [ ] str , int k ) { 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 ] ) { char t = str [ i ] ; str [ i ] = str [ j ] ; str [ j ] = t ; if ( String . valueOf ( str ) . compareTo ( max ) > 0 ) max = String . valueOf ( str ) ; findMaximumNum ( str , k - 1 ) ; char c = str [ i ] ; str [ i ] = str [ j ] ; str [ j ] = c ; } } } } public static void main ( String [ ] args ) { String str = "129814999" ; int k = 4 ; max = str ; findMaximumNum ( str . toCharArray ( ) , k ) ; System . out . print ( max + "NEW_LINE"); } }