Skip to content

Instantly share code, notes, and snippets.

@rajatdiptabiswas
Created July 28, 2018 05:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rajatdiptabiswas/850a875af17c48186d4902d24395e84d to your computer and use it in GitHub Desktop.
Save rajatdiptabiswas/850a875af17c48186d4902d24395e84d to your computer and use it in GitHub Desktop.
Given a permutation of first n natural numbers as array and an integer k. Print the lexicographically largest permutation after at most k swaps (https://www.geeksforgeeks.org/largest-permutation-k-swaps/)
import java.util.*;
import java.io.*;
import java.lang.*;
public class kSwapLargestPermutation {
public static void main(String[] args) {
Integer[] numberArray = new Integer[] {4, 5, 2, 1, 3};
Integer k = 3;
Integer n = Collections.max(Arrays.asList(numberArray)); // get the maximum element
Integer[] position = new Integer[n+1]; // create position array with position for elements 0 to n
for (int x = 0; x < n; x++) {
position[numberArray[x]] = x; // fill the position array with position of elements
}
for (int i = 0; i < n && k > 0; i++) {
if (numberArray[i] == n-i) {
continue; // if the element in the number array is already the largest then skip forward
}
// swap the position of current element and max element
Integer temp = position[n-i]; // store position of max element
position[n-i] = position[numberArray[i]];
position[numberArray[i]] = temp;
// swap elements in number array using position of max element and position of current element
Integer tempNumber = numberArray[temp];
numberArray[temp] = numberArray[i];
numberArray[i] = tempNumber;
for (Integer a : numberArray)
System.out.print(a + " ");
System.out.println();
k--; // decrement k to keep track of swaps
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment