forked from namishkhanna/hacktoberfest2020
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKLargestElements.java
More file actions
35 lines (29 loc) · 816 Bytes
/
KLargestElements.java
File metadata and controls
35 lines (29 loc) · 816 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
//Hacktober Fest 2020
import java.util.PriorityQueue;
import java.util.Scanner;
public class KLargestElements {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
for(int i=0; i<arr.length;i++){
arr[i] = sc.nextInt();
}
int k = sc.nextInt();
PriorityQueue<Integer> pq = new PriorityQueue<>();
for (int i =0;i< arr.length;i++){
if (i<k){
pq.add(arr[i]);
}
else {
if (arr[i]> pq.peek()){
pq.remove();
pq.add(arr[i]);
}
}
}
while (pq.size()>0){
System.out.println(pq.remove());
}
}
}