Problem Statement
You are given an array of N integers which is a permutation of the first N natural numbers. You can swap any two elements of the array. You can make at most K swaps. What is the largest permutation, in numerical order, you can make?
Input Format
The first line of the input contains two integers,N and K , the size of the input array and the maximum swaps you can make, respectively. The second line of the input contains a permutation of the first N natural numbers.
The first line of the input contains two integers,
Output Format
Print the lexicographically largest permutation you can make with at mostK swaps.
Print the lexicographically largest permutation you can make with at most
Constraints
1≤N≤105
1≤K≤109
Sample Input#00
5 1
4 2 3 5 1
Sample Output#00
5 2 3 4 1
Explanation#00
You can swap any two numbers in[4,2,3,5,1] and see the largest permutation is [5,2,3,4,1]
You can swap any two numbers in
Sample Input#01
3 1
2 1 3
Sample Output#01
3 1 2
Explanation#01
With 1 swap we can get[1,2,3] , [3,1,2] and [2,3,1] out of these [3,1,2] is the largest permutation.
With 1 swap we can get
Sample Input#02
2 1
2 1
Sample Output#02
2 1
Explanation#02
We can see that[2,1] is already the largest permutation. So we don't need any swaps.
We can see that
Copyright © 2015 HackerRank.
All Rights Reserved
All Rights Reserved
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) throws IOException{
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
String[] in = s.split(" ");
int n = Integer.parseInt(in[0]);
long k = Integer.parseInt(in[1]);
s = br.readLine();
String[] tmp = s.split(" ");
long[] num = new long[n];
for(int i = 0 ; i < n ; i++)
{
num[i] = Integer.parseInt(tmp[i]);
}
if( k > n)
k = n;
for(int i = 0 ; i < k ; i++)
{
int pos = i;
for(int j = i ; j < n ; j++)
{
if(num[j] > num[pos])
{
pos = j ;
}
}
if(pos != i)
{
long t = num[i];
num[i] = num[pos];
num[pos] = t;
}
else
{
k++;
if(k >= n)
k = n ;
}
}
for(int i = 0 ; i < n ; i++)
{
System.out.print(num[i]+" ");
}
}
}
No comments:
Post a Comment