Skip to content

Instantly share code, notes, and snippets.

@cc2011
Created March 26, 2015 22:14
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save cc2011/e4bf29e97056a1b4f448 to your computer and use it in GitHub Desktop.
//https://www.hackerrank.com/challenges/largest-permutation
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
try {
Scanner s = new Scanner(System.in);
String[] inputArr = s.nextLine().split(" ");
int n = Integer.parseInt(inputArr[0]) ;
int k = Integer.parseInt(inputArr[1]);
inputArr = s.nextLine().split(" ");
int[] input = new int[n];
for(int j=0; j < n;j++) {
input[j] = Integer.parseInt(inputArr[j]);
}
for(int j=0;j < n; j++) {
int swapIndex = existLargest(input[j],j,input);
if(swapIndex != j) {
if(k!=0){
int temp = input[j];
input[j] = input[swapIndex];
input[swapIndex]= temp;
k--;
} else {
break;
}
}
}
for(int j=0;j < n;j++) {
if(j >0)
System.out.print(" ");
System.out.print(input[j]);
}
System.out.println();
} catch(Exception e){
e.printStackTrace();
}
}
public static int existLargest(int curr,int index,int[] arr) {
int output = curr;
int outputIndex = index;
for(int i=index+1; i < arr.length;i++){
if(output < arr[i]){
output = arr[i];
outputIndex = i;
}
}
return outputIndex;
}
}
@ozishan91
Copy link

Hi,
Three test cases are getting timed out .

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment