Largest permutation after at most k swaps | Function to find the largest permutation after k swaps ; Storing the elements and their index in map ; If number of swaps allowed are equal to number of elements then the resulting permutation will be descending order of given permutation . ; If j is not at it 's best index ; Change the index of the element which was at position 0. Swap the element basically . ; Decrement number of swaps ; Driver Code ; K is the number of swaps ; n is the size of the array ; Function calling
def bestpermutation ( arr , k , n ) : NEW_LINE INDENT h = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT h [ arr [ i ] ] = i NEW_LINE DEDENT if ( n <= k ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE arr . reverse ( ) NEW_LINE DEDENT else : NEW_LINE INDENT for j in range ( n , 0 , - 1 ) : NEW_LINE INDENT if ( k > 0 ) : NEW_LINE INDENT initial_index = h [ j ] NEW_LINE best_index = n - j NEW_LINE if ( initial_index != best_index ) : NEW_LINE INDENT h [ j ] = best_index NEW_LINE element = arr [ best_index ] NEW_LINE h [ element ] = initial_index NEW_LINE arr [ best_index ] , arr [ initial_index ] = ( arr [ initial_index ] , arr [ best_index ] ) NEW_LINE k -= 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT arr = [ 3 , 1 , 4 , 2 , 5 ] NEW_LINE k = 10 NEW_LINE n = len ( arr ) NEW_LINE bestpermutation ( arr , k , n ) NEW_LINE print ( " Largest ▁ possible ▁ permutation ▁ after " , k , " swaps ▁ is " , end = " ▁ " ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT