hackerrank [Greedy] https://www.hackerrank.com/challenges/largest-permutation
This file contains 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
//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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi,
Three test cases are getting timed out .