Problem:
Given an array, print k largest elements from the array. The output elements should be printed in decreasing order.
Input:
The first line of input contains an integer T denoting the number of test cases.
The first line of each test case is N and k, N is the size of array and K is the largest elements to be returned.
The second line of each test case contains N input C[i].
Output:
Print the k largest element in descending order.
Constraints:
1 ≤ T ≤ 100
1 ≤ N ≤ 100
K ≤ N
1 ≤ C[i] ≤ 1000
Example:
Input:
2
5 2
12 5 787 1 23
7 3
1 23 12 9 30 2 50
Output:
787 23
50 30 23
Solution program below:
package test;
import java.util.Comparator;
import java.util.Scanner;
import static java.util.Arrays.sort;
public class KLargestElement {
public static void sortNumberUpToGivenNumber(Integer[] inputArray, int K) {
sort(inputArray, new Comparator<Integer>(){
@Override
public int compare(Integer i1, Integer i2) {
return i2.compareTo(i1);//sort in reverse
}
});
for (int a = 0; a < K; a++)
System.out.print(inputArray[a] + " ");
System.out.println();
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter number of test cases: ");
int T = scanner.nextInt();
for(int i = 0; i < T; i++) {
int N = scanner.nextInt();
int K = scanner.nextInt();
// create an array of size N
Integer[] array = new Integer[N];
//store numbers and sort upto the given number
for (int j = 0; j < N; j++) {
array[j] = scanner.nextInt();
}
if(K <= N)
sortNumberUpToGivenNumber(array, K);
else
System.out.println("Wrong entry! Please try again.");
}
}
}
Sample Input:
2
5 2
12 5 787 1 23
7 3
1 23 12 9 30 2 50
Output:
787 23
50 30 23
Comments
Post a Comment