Given a permutation of first n natural numbers as array and an integer k. Print the lexicographically largest permutation after at most k swaps
Examples:
Input: arr[] = {4, 5, 2, 1, 3}
k = 3
Output: 5 4 3 2 1
Swap 1st and 2nd elements: 5 4 2 1 3
Swap 3rd and 5th elements: 5 4 3 1 2
Swap 4th and 5th elements: 5 4 3 2 1
Input: arr[] = {2, 1, 3}
k = 1
Output: 3 1 2
Swap 1st and 3re elements: 3 1 2
Naive approach: The idea is to generate one by one permutation in lexicographically decreasing order. Compare every generated permutation with original array and count the number of swaps required to convert. If count is less than or equal to k, print this permutation. The problem of this approach is that it would be difficult to implement and will definitely time out for the large value of N.
Algorithm:
- To find the minimum swaps to convert one array to another read this article.
- Copy the original array and sort that array in decreasing order. So the sorted array is the largest permutation of the original array.
- Now generate all permutation in lexicographically decreasing order. Previous permutation is calculated using prev_permutation() function.
- Find the minimum steps required to convert the new array (permutation in decreasing order) to original array, if the count is less than or equal to k. Then print the array and break.
Implementation:
C++14
#include <bits/stdc++.h>
using namespace std;
int minSwapsToSort( int arr[], int n)
{
pair< int , int > arrPos[n];
for ( int i = 0; i < n; i++) {
arrPos[i].first = arr[i];
arrPos[i].second = i;
}
sort(arrPos, arrPos + n);
vector< bool > vis(n, false );
int ans = 0;
for ( int i = 0; i < n; i++) {
if (vis[i] || arrPos[i].second == i)
continue ;
int cycle_size = 0;
int j = i;
while (!vis[j]) {
vis[j] = 1;
j = arrPos[j].second;
cycle_size++;
}
ans += (cycle_size - 1);
}
return ans;
}
int minSwapToMakeArraySame(
int a[], int b[], int n)
{
map< int , int > mp;
for ( int i = 0; i < n; i++)
mp[b[i]] = i;
for ( int i = 0; i < n; i++)
b[i] = mp[a[i]];
return minSwapsToSort(b, n);
}
void KswapPermutation(
int arr[], int n, int k)
{
int a[n];
for ( int i = 0; i < n; i++)
a[i] = arr[i];
sort(arr, arr + n, greater< int >());
do {
int a1[n], b1[n];
for ( int i = 0; i < n; i++) {
a1[i] = arr[i];
b1[i] = a[i];
}
if (
minSwapToMakeArraySame(
a1, b1, n)
<= k) {
for ( int i = 0; i < n; i++)
cout << arr[i] << " " ;
break ;
}
} while (prev_permutation(arr, arr + n));
}
int main()
{
int arr[] = { 4, 5, 2, 1, 3 };
int n = sizeof (arr) / sizeof (arr[0]);
int k = 3;
cout << "Largest permutation after "
<< k << " swaps:\n" ;
KswapPermutation(arr, n, k);
return 0;
}
|
Java
import java.util.*;
public class Solution {
static class Pair {
int first, second;
Pair( int f, int s)
{
first = f;
second = s;
}
}
static int minSwapsToSort( int arr[], int n)
{
ArrayList<Pair> arrPos = new ArrayList<>();
for ( int i = 0 ; i < n; i++) {
arrPos.add( new Pair(arr[i], i));
}
Collections.sort(arrPos, (Pair A, Pair B) -> {
return A.first - B.first;
});
boolean [] vis = new boolean [n];
int ans = 0 ;
for ( int i = 0 ; i < n; i++) {
if (vis[i] || arrPos.get(i).second == i)
continue ;
int cycle_size = 0 ;
int j = i;
while (!vis[j]) {
vis[j] = true ;
j = arrPos.get(j).second;
cycle_size++;
}
ans += (cycle_size - 1 );
}
return ans;
}
static int minSwapToMakeArraySame( int a[], int b[],
int n)
{
HashMap<Integer, Integer> mp = new HashMap<>();
for ( int i = 0 ; i < n; i++)
mp.put(b[i], i);
for ( int i = 0 ; i < n; i++)
b[i] = mp.get(a[i]);
return minSwapsToSort(b, n);
}
static void KswapPermutation( int [] arr, int n, int k)
{
int a[] = new int [n];
for ( int i = 0 ; i < n; i++)
a[i] = arr[i];
Arrays.sort(arr);
for ( int idx = 0 ; idx < n / 2 ; idx++) {
int t = arr[idx];
arr[idx] = arr[n - idx - 1 ];
arr[n - idx - 1 ] = t;
}
do {
int [] a1 = new int [n];
int [] b1 = new int [n];
for ( int i = 0 ; i < n; i++) {
a1[i] = arr[i];
b1[i] = a[i];
}
if (minSwapToMakeArraySame(a1, b1, n) <= k) {
for ( int i = 0 ; i < n; i++)
System.out.print(arr[i] + " " );
break ;
}
} while (prev_permutation(arr, n));
}
static boolean prev_permutation( int [] s, int n)
{
int i = n - 1 ;
while (i > 0 && s[i - 1 ] <= s[i]) {
if (--i == 0 ) {
return false ;
}
}
int j = i;
while (j < n && s[j] <= s[i - 1 ]) {
j++;
}
j--;
int t = s[i - 1 ];
s[i - 1 ] = s[j];
s[j] = t;
int l = i;
int r = n - 1 ;
while (l < r) {
t = s[l];
s[l] = s[r];
s[r] = t;
l++;
r--;
}
return true ;
}
public static void main(String[] args)
{
int arr[] = { 2 , 1 , 3 };
int n = arr.length;
int k = 1 ;
System.out.println( "Largest permutation after " + k
+ " swaps:" );
KswapPermutation(arr, n, k);
}
}
|
Python3
def min_swaps_to_sort(arr, n):
arr_pos = [(arr[i], i) for i in range (n)]
arr_pos.sort(key = lambda x: x[ 0 ])
vis = [ False ] * n
ans = 0
for i in range (n):
if vis[i] or arr_pos[i][ 1 ] = = i:
continue
cycle_size = 0
j = i
while not vis[j]:
vis[j] = True
j = arr_pos[j][ 1 ]
cycle_size + = 1
ans + = (cycle_size - 1 )
return ans
def min_swap_to_make_array_same(a, b, n):
mp = {b[i]: i for i in range (n)}
for i in range (n):
b[i] = mp[a[i]]
return min_swaps_to_sort(b, n)
def k_swap_permutation(arr, n, k):
a = arr.copy()
arr.sort(reverse = True )
while True :
a1 = arr.copy()
b1 = a.copy()
if min_swap_to_make_array_same(a1, b1, n) < = k:
return arr
break
if not prev_permutation(arr):
break
arr = [ 4 , 5 , 2 , 1 , 3 ]
n = len (arr)
k = 3
print ( "Largest permutation after" , k, "swaps:" )
print (k_swap_permutation(arr, n, k))
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
public class GFG
{
class Pair
{
public int first, second;
public Pair( int f, int s)
{
first = f;
second = s;
}
}
static int minSwapsToSort( int [] arr, int n)
{
List<Pair> arrPos = new List<Pair>();
for ( int i = 0; i < n; i++)
{
arrPos.Add( new Pair(arr[i], i));
}
arrPos.Sort((Pair A, Pair B) => {
return A.first - B.first;
});
bool [] vis = new bool [n];
int ans = 0;
for ( int i = 0; i < n; i++)
{
if (vis[i] || arrPos[i].second == i)
continue ;
int cycle_size = 0;
int j = i;
while (!vis[j])
{
vis[j] = true ;
j = arrPos[j].second;
cycle_size++;
}
ans += (cycle_size - 1);
}
return ans;
}
static int minSwapToMakeArraySame( int [] a, int [] b,
int n)
{
Dictionary< int , int > mp = new Dictionary< int , int >();
for ( int i = 0; i < n; i++)
mp.Add(b[i], i);
for ( int i = 0; i < n; i++)
b[i] = mp[a[i]];
return minSwapsToSort(b, n);
}
static void KswapPermutation( int [] arr, int n, int k)
{
int [] a = new int [n];
for ( int i = 0; i < n; i++)
a[i] = arr[i];
Array.Sort(arr);
for ( int idx = 0; idx < n / 2; idx++)
{
int t = arr[idx];
arr[idx] = arr[n - idx - 1];
arr[n - idx - 1] = t;
}
do
{
int [] a1 = new int [n];
int [] b1 = new int [n];
for ( int i = 0; i < n; i++)
{
a1[i] = arr[i];
b1[i] = a[i];
}
if (minSwapToMakeArraySame(a1, b1, n) <= k)
{
for ( int i = 0; i < n; i++)
Console.Write(arr[i] + " " );
break ;
}
} while (prev_permutation(arr, n));
}
static bool prev_permutation( int [] s, int n)
{
int i = n - 1;
while (i > 0 && s[i - 1] <= s[i])
{
if (--i == 0)
{
return false ;
}
}
int j = i;
while (j < n && s[j] <= s[i - 1])
{
j++;
}
j--;
int t = s[i - 1];
s[i - 1] = s[j];
s[j] = t;
int l = i;
int r = n - 1;
while (l < r)
{
t = s[l];
s[l] = s[r];
s[r] = t;
l++;
r--;
}
return true ;
}
static public void Main()
{
int [] arr = { 2, 1, 3 };
int n = arr.Length;
int k = 1;
Console.WriteLine( "Largest permutation after " + k
+ " swaps:" );
KswapPermutation(arr, n, k);
}
}
|
Javascript
function minSwapsToSort(arr, n)
{
let arrPos = new Array(n);
for (let i = 0; i < n; i++) {
arrPos[i] = {first: arr[i], second: i};
}
arrPos.sort((a, b) => a.first - b.first);
let vis = new Array(n).fill( false );
let ans = 0;
for (let i = 0; i < n; i++) {
if (vis[i] || arrPos[i].second === i)
continue ;
let cycle_size = 0;
let j = i;
while (!vis[j]) {
vis[j] = true ;
j = arrPos[j].second;
cycle_size++;
}
ans += (cycle_size - 1);
}
return ans;
}
function minSwapToMakeArraySame(a, b, n) {
let mp = new Map();
for (let i = 0; i < n; i++)
mp.set(b[i], i);
for (let i = 0; i < n; i++)
b[i] = mp.get(a[i]);
return minSwapsToSort(b, n);
}
function KswapPermutation(arr, n, k) {
let a = arr.slice();
arr.sort();
arr.reverse();
do {
let a1 = [0]*n;
let b1 = [0]*n;
for (let i = 0; i < n; i++) {
a1[i] = arr[i];
b1[i] = a[i];
}
if (
minSwapToMakeArraySame(
a1, b1, n)
<= k) {
console.log(arr);
break ;
}
} while (prev_permutation(arr, arr + n));
}
let arr = [ 4, 5, 2, 1, 3 ];
let n = arr.length;
let k = 3;
console.log( "Largest permutation after" ,k, "swaps:" );
KswapPermutation(arr, n, k);
|
OutputLargest permutation after 3 swaps:
5 4 3 2 1
Complexity Analysis:
- Time Complexity: O(N!).
To generate all permutation O(N!) time complexity is required. - Space Complexity: O(n).
to store the new array O(n) space is required.
Another approach worth considering :
This problem can be considered as an instance of a “controlled” selection sort . By controlled , we mean that we are not performing the selection sort operation on the entire array. Instead, we are constructing ourselves to only the total number of swaps K that we are allowed to perform.
So in the following approach , all we need to do is simply let the selection sort go on for k times , not more than that . Also we need to check if the position of the maximum number we’re about to swap with the current position i is equal to the number already present in that position , and we need to jump over this particular situation , nevertheless we shouldn’t waste our limited number of swaps .
Implementation:
C++14
#include <bits/stdc++.h>
using namespace std;
void KswapPermutation(
int arr[], int n, int k)
{
for ( int i=0;i<n-1;i++)
{
if ( k>0)
{
int max = i;
for ( int j=i+1;j<n;j++)
if (arr[j]>arr[max])
max = j;
if (max!=i)
{
int temp = arr[max];
arr[max] = arr[i];
arr[i] = temp;
k--;
}
}
else
break ;
}
}
int main()
{
int arr[] = { 4, 5, 2, 1, 3 };
int n = sizeof (arr) / sizeof (arr[0]);
int k = 3;
KswapPermutation(arr, n, k);
cout << "Largest permutation after "
<< k << " swaps:" <<endl;
for ( int i = 0; i < n; ++i)
cout<<arr[i]<< " " ;
return 0;
}
|
Java
import java.io.*;
class GFG {
static void KswapPermutation( int arr[], int n, int k)
{
for ( int i = 0 ; i < n - 1 ; i++) {
if (k > 0 ) {
int max = i;
for ( int j = i + 1 ; j < n; j++)
if (arr[j] > arr[max])
max = j;
if (max != i) {
int temp = arr[max];
arr[max] = arr[i];
arr[i] = temp;
k--;
}
}
else
break ;
}
}
public static void main(String[] args)
{
int arr[] = { 4 , 5 , 2 , 1 , 3 };
int n = arr.length;
int k = 3 ;
KswapPermutation(arr, n, k);
System.out.println( "Largest permutation after " + k
+ " swaps:" );
for ( int i = 0 ; i < n; ++i)
System.out.print(arr[i] + " " );
}
}
|
Python3
def KswapPermutation(arr, n, k):
for i in range ( 0 , n - 1 ):
if (k > 0 ):
max = i
for j in range (i + 1 , n):
if (arr[j] > arr[ max ]):
max = j
if ( max ! = i):
temp = arr[ max ]
arr[ max ] = arr[i]
arr[i] = temp
k = k - 1
else :
break
arr = [ 4 , 5 , 2 , 1 , 3 ]
n = len (arr)
k = 3
KswapPermutation(arr, n, k)
print ( "Largest permutation after " + str (k) + " swaps:" )
for i in range ( 0 , n):
print (arr[i], end = ' ' )
|
C#
using System;
using System.Collections.Generic;
class GFG {
static void KswapPermutation( int [] arr, int n, int k)
{
for ( int i = 0; i < n - 1; i++) {
if (k > 0) {
int max = i;
for ( int j = i + 1; j < n; j++)
if (arr[j] > arr[max]) {
max = j;
}
if (max != i) {
int temp = arr[max];
arr[max] = arr[i];
arr[i] = temp;
k--;
}
}
else
break ;
}
}
public static void Main( string [] args)
{
int [] arr = { 4, 5, 2, 1, 3 };
int n = 5;
int k = 3;
KswapPermutation(arr, n, k);
Console.WriteLine( "Largest permutation after " + k
+ " swaps:" );
for ( int i = 0; i < n; i++)
Console.Write(arr[i] + " " );
}
}
|
Javascript
<script>
function KswapPermutation(arr, n, k)
{
for (let i=0;i<n-1;i++)
{
if ( k>0)
{
let max = i;
for (let j=i+1;j<n;j++)
if (arr[j]>arr[max])
max = j;
if (max!=i)
{
let temp = arr[max];
arr[max] = arr[i];
arr[i] = temp;
k--;
}
}
else
break ;
}
}
let arr = [ 4, 5, 2, 1, 3 ];
let n = 5;
let k = 3;
KswapPermutation(arr, n, k);
document.write( "Largest permutation after " + k + " swaps:" );
document.write(arr);
</srcipt>
|
OutputLargest permutation after 3 swaps:
5 4 3 2 1
Complexity analysis :
- Time complexity : O(n^2) , because this approach utilizes selection sort
- Space complexity : O(1) , because the sort is in place and no extra space is needed
Efficient approach:
This is a greedy approach. The largest permutation is found when the largest elements are at the front of the array, i.e. the largest elements are sorted in decreasing order. There are at most k swaps so put the 1st, 2nd, 3rd, …, kth largest element at their respective position.
Note: If the number of swaps allowed is equal to the size of the array, then there is no need to iterate over the whole array. The answer will simply be the reverse sorted array.
Algorithm:
- Create a HashMap or an array of length n to store element-index pair or map element to its index.
- Now run a loop k times.
- In each iteration swap the ith element with the element n – i. where i is the index or count of the loop. Also swap their position, i.e. update the hashmap or array. So in this step the largest element in remaining element is swapped to the front.
- Print the output array.
Implementation 1: This uses simple arrays to arrive at the solution.
C++
#include <bits/stdc++.h>
using namespace std;
void KswapPermutation(
int arr[], int n, int k)
{
int pos[n + 1];
for ( int i = 0; i < n; ++i)
pos[arr[i]] = i;
for ( int i = 0; i < n && k; ++i) {
if (arr[i] == n - i)
continue ;
int temp = pos[n - i];
pos[arr[i]] = pos[n - i];
pos[n - i] = i;
swap(arr[temp], arr[i]);
--k;
}
}
int main()
{
int arr[] = { 4, 5, 2, 1, 3 };
int n = sizeof (arr) / sizeof (arr[0]);
int k = 3;
KswapPermutation(arr, n, k);
cout << "Largest permutation after "
<< k << " swaps:n" ;
for ( int i = 0; i < n; ++i)
printf ( "%d " , arr[i]);
return 0;
}
|
Java
class GFG {
static void KswapPermutation(
int arr[], int n, int k)
{
int pos[] = new int [n + 1 ];
for ( int i = 0 ; i < n; ++i)
pos[arr[i]] = i;
for ( int i = 0 ; i < n && k > 0 ; ++i) {
if (arr[i] == n - i)
continue ;
int temp = pos[n - i];
pos[arr[i]] = pos[n - i];
pos[n - i] = i;
int tmp1 = arr[temp];
arr[temp] = arr[i];
arr[i] = tmp1;
--k;
}
}
public static void main(String[] args)
{
int arr[] = { 4 , 5 , 2 , 1 , 3 };
int n = arr.length;
int k = 3 ;
KswapPermutation(arr, n, k);
System.out.print(
"Largest permutation "
+ "after " + k + " swaps:\n" );
for ( int i = 0 ; i < n; ++i)
System.out.print(arr[i] + " " );
}
}
|
Python3
def KswapPermutation(arr, n, k):
pos = {}
for i in range (n):
pos[arr[i]] = i
for i in range (n):
if k = = 0 :
break
if (arr[i] = = n - i):
continue
temp = pos[n - i]
pos[arr[i]] = pos[n - i]
pos[n - i] = i
arr[temp], arr[i] = arr[i], arr[temp]
k = k - 1
arr = [ 4 , 5 , 2 , 1 , 3 ]
n = len (arr)
k = 3
KswapPermutation(arr, n, k)
print ( "Largest permutation after" , k, "swaps: " )
print ( " " .join( map ( str , arr)))
|
C#
using System;
class GFG {
static void KswapPermutation( int [] arr,
int n, int k)
{
int [] pos = new int [n + 1];
for ( int i = 0; i < n; ++i)
pos[arr[i]] = i;
for ( int i = 0; i < n && k > 0; ++i) {
if (arr[i] == n - i)
continue ;
int temp = pos[n - i];
pos[arr[i]] = pos[n - i];
pos[n - i] = i;
int tmp1 = arr[temp];
arr[temp] = arr[i];
arr[i] = tmp1;
--k;
}
}
public static void Main()
{
int [] arr = { 4, 5, 2, 1, 3 };
int n = arr.Length;
int k = 3;
KswapPermutation(arr, n, k);
Console.Write( "Largest permutation "
+ "after " + k + " swaps:\n" );
for ( int i = 0; i < n; ++i)
Console.Write(arr[i] + " " );
}
}
|
PHP
<?php
function KswapPermutation(& $arr , $n , $k )
{
for ( $i = 0; $i < $n ; ++ $i )
$pos [ $arr [ $i ]] = $i ;
for ( $i = 0; $i < $n && $k ; ++ $i )
{
if ( $arr [ $i ] == $n - $i )
continue ;
$temp = $pos [ $n - $i ];
$pos [ $arr [ $i ]] = $pos [ $n - $i ];
$pos [ $n - $i ] = $i ;
$t = $arr [ $temp ];
$arr [ $temp ] = $arr [ $i ];
$arr [ $i ] = $t ;
-- $k ;
}
}
$arr = array (4, 5, 2, 1, 3);
$n = sizeof( $arr );
$k = 3;
KswapPermutation( $arr , $n , $k );
echo ( "Largest permutation after " );
echo ( $k );
echo ( " swaps:\n" );
for ( $i = 0; $i < $n ; ++ $i )
{
echo ( $arr [ $i ] );
echo ( " " );
}
?>
|
Javascript
function KswapPermutation(arr, n, k)
{
let pos = new Array(n + 1);
for (let i = 0; i < n; ++i)
pos[arr[i]] = i;
for (let i = 0; i < n && k; ++i) {
if (arr[i] == n - i)
continue ;
let temp = pos[n - i];
pos[arr[i]] = pos[n - i];
pos[n - i] = i;
let tmp1 = arr[temp];
arr[temp] = arr[i];
arr[i] = tmp1;
--k;
}
}
let arr = [ 4, 5, 2, 1, 3 ];
let n = arr.length;
let k = 3;
KswapPermutation(arr, n, k);
console.log( "Largest permutation after " + k + " swaps:" + "</br>" );
for (let i = 0; i < n; ++i)
console.log(arr[i] + " " );
|
OutputLargest permutation after 3 swaps:n5 4 3 2 1
Time complexity :- O(nlogn)
Space complexity :- O(N)
Implementation 2: This uses a hashmap to arrive at the solution.
C++
#include <bits/stdc++.h>
#include <unordered_map>
using namespace std;
void bestpermutation(
int arr[], int k, int n)
{
unordered_map< int , int > h;
for ( int i = 0; i < n; i++) {
h.insert(make_pair(arr[i], i));
}
if (n <= k) {
sort(arr, arr + n, greater< int >());
}
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;
swap(
arr[best_index],
arr[initial_index]);
k--;
}
}
}
}
}
int main()
{
int arr[] = { 3, 1, 4, 2, 5 };
int k = 10;
int n = sizeof (arr) / sizeof ( int );
bestpermutation(arr, k, n);
cout << "Largest possible permutation after "
<< k << " swaps is " ;
for ( int i = 0; i < n; i++)
cout << arr[i] << " " ;
return 0;
}
|
Java
import java.util.*;
class GFG
{
static void bestpermutation(ArrayList<Integer> arr, int k, int n)
{
HashMap<Integer, Integer> h =
new HashMap<Integer, Integer>();
for ( int i = 0 ; i < n; i++)
{
h.put(arr.get(i), i);
}
if (n <= k) {
Collections.sort(arr, Collections.reverseOrder());
}
else {
for ( int j = n; j >= 1 ; j--)
{
if (k > 0 )
{
int initial_index = h.get(j);
int best_index = n - j;
if (initial_index != best_index)
{
h.put(j, best_index);
int element = arr.get(best_index);
h.put(element, initial_index);
int temp = arr.get(best_index);
arr.set(best_index, arr.get(initial_index));
arr.set(initial_index, temp);
k--;
}
}
}
}
}
public static void main(String []args)
{
ArrayList<Integer> arr = new ArrayList<Integer>();
arr.add( 3 );
arr.add( 1 );
arr.add( 4 );
arr.add( 2 );
arr.add( 5 );
int k = 10 ;
int n = arr.size();
bestpermutation(arr, k, n);
System.out.print( "Largest possible permutation after " + k + " swaps is " );
for ( int i = 0 ; i < n; i++)
System.out.print(arr.get(i) + " " );
}
}
|
Python3
def bestpermutation(arr, k, n):
h = {}
for i in range (n):
h[arr[i]] = i
if (n < = k):
arr.sort()
arr.reverse()
else :
for j in range (n, 0 , - 1 ):
if (k > 0 ):
initial_index = h[j]
best_index = n - j
if (initial_index ! = best_index):
h[j] = best_index
element = arr[best_index]
h[element] = initial_index
arr[best_index], arr[initial_index] = (arr[initial_index],
arr[best_index])
k - = 1
arr = [ 3 , 1 , 4 , 2 , 5 ]
k = 10
n = len (arr)
bestpermutation(arr, k, n)
print ( "Largest possible permutation after" ,
k, "swaps is" , end = " " )
for i in range (n):
print (arr[i], end = " " )
|
C#
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] + " " );
}
}
|
Javascript
<script>
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(
"Largest possible permutation after " + k + " swaps is "
);
for (let i = 0; i < n; i++)
document.write(arr[i] + " " );
</script>
|
OutputLargest possible permutation after 10 swaps is 5 4 3 2 1
Complexity Analysis:
- Time Complexity: O(N).
Only one traversal of the array is required. - Space Complexity: O(n).
To store the new array O(n) space is required.
This article is contributed by Shubham Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.