Skip to content

Commit 1fc9d37

Browse files
authored
Create K largest Element.java
1 parent 3f84d8a commit 1fc9d37

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

Heap/K largest Element.java

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
// Heap Questions:::
2+
//Problem Statement :: K largest Element in given array.
3+
// IP : arr[] =7 10 4 3 20 15 ,k=3
4+
// OP : 10,20,15
5+
6+
//TC : O(nlogk)
7+
//SC : O(k)
8+
import java.util.*;
9+
public class Main
10+
{
11+
public static void main(String[] args) {
12+
int arr[] = new int[]{6,10,4,3,20,15,21,18,2};
13+
int k=5;
14+
kthSmallestele(arr,k);
15+
//Lets Check :: 2,3,4,6,10,15,18,20,21
16+
}
17+
public static void kthSmallestele(int[] arr,int k){
18+
//Largest given:: so we will make min heap::
19+
PriorityQueue<Integer> minheap =new PriorityQueue<>();
20+
for(int i=0;i<arr.length;i++){
21+
minheap.add(arr[i]);
22+
if(minheap.size()>k){
23+
minheap.poll();
24+
}
25+
}
26+
while(!minheap.isEmpty()){
27+
System.out.print(minheap.poll()+" ");
28+
}
29+
}
30+
}
31+
/*
32+
10 15 18 20 21
33+
*/

0 commit comments

Comments
 (0)