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
function bestpermutation ( arr , k , n ) { let h = new Map ( ) ; for ( let i = 0 ; i < n ; i ++ ) { h . set ( arr [ i ] , i ) ; } if ( n <= k ) { arr . sort ( function ( a , b ) { return b - a ; } ) ; } else { for ( let j = n ; j >= 1 ; j -- ) { if ( k > 0 ) { let initial_index = h [ j ] ; let best_index = n - j ; if ( initial_index != best_index ) { h . set ( j , best_index ) ; let element = arr . get ( best_index ) ; h . set ( element , initial_index ) ; let temp = arr [ best_index ] ; arr . set ( best_index , arr [ initial_index ] ) ; arr . set ( initial_index , temp ) ; k -- ; } } } } } let arr = [ 3 , 1 , 4 , 2 , 5 ] ; let k = 10 ; let n = arr . length ; bestpermutation ( arr , k , n ) ; document . write ( " " + k + " " ) ; for ( let i = 0 ; i < n ; i ++ ) document . write ( arr [ i ] + " " ) ;