Created
July 28, 2018 05:49
-
-
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/)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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