forked from dark-knight009/Programming-Helpers
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathK_Largest_Elements.java
More file actions
46 lines (42 loc) · 1.04 KB
/
Copy pathK_Largest_Elements.java
File metadata and controls
46 lines (42 loc) · 1.04 KB
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
36
37
38
39
40
41
42
43
44
45
46
// Required Time Complexity -> O(nlogk).
// For this sorting and then printing the last k elements will also help us
// but it will result in O(nlogn) time complexity.
//Input--> 6 5 4 1 2 8
// k = 2
//Output-> 6 8
import java.util.*;
public class K_Largest_Elements
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] Ar = new int[n];
for(int i = 0;i<n;i++)
{
Ar[i] = sc.nextInt();
}
int k = sc.nextInt();
PriorityQueue<Integer> pq = new PriorityQueue<>();
for(int i=0;i<n;i++)
{
if(i<k)
{
pq.add(Ar[i]);
}
else
{
if(Ar[i]>pq.peek())
{
pq.remove();
pq.add(Ar[i]);
}
}
}
while(pq.size()>0)
{
System.out.println(pq.peek());
pq.remove();
}
}
}