Largest permutation after at most k swaps | C # Program to find the largest permutation after at most k swaps using unordered_map . ; 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
using System ; using System . Collections . Generic ; class GFG { static void bestpermutation ( List < int > arr , int k , int n ) { Dictionary < int , int > h = new Dictionary < int , int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { h . Add ( arr [ i ] , i ) ; } if ( n <= k ) { arr . Sort ( ) ; arr . Reverse ( ) ; } else { for ( int j = n ; j >= 1 ; j -- ) { if ( k > 0 ) { int initial_index = h [ j ] ; int best_index = n - j ; if ( initial_index != best_index ) { h [ j ] = best_index ; int element = arr [ best_index ] ; h [ element ] = initial_index ; int temp = arr [ best_index ] ; arr [ best_index ] = arr [ initial_index ] ; arr [ initial_index ] = temp ; k -- ; } } } } } static void Main ( ) { List < int > arr = new List < int > ( new int [ ] { 3 , 1 , 4 , 2 , 5 } ) ; int k = 10 ; int n = arr . Count ; bestpermutation ( arr , k , n ) ; Console . Write ( " Largest ▁ possible ▁ permutation ▁ after ▁ " + k + " ▁ swaps ▁ is ▁ " ) ; for ( int i = 0 ; i < n ; i ++ ) Console . Write ( arr [ i ] + " ▁ " ) ; } }