File tree Expand file tree Collapse file tree 2 files changed +52
-0
lines changed
Expand file tree Collapse file tree 2 files changed +52
-0
lines changed Original file line number Diff line number Diff line change 1+ /*
2+ author:gulshan yadav
3+ email: gulshany01@gmail.com
4+ date: 21-July-2021
5+ */
6+ #include < iostream>
7+ #include < bits/stdc++.h>
8+ using namespace std ;
9+
10+ void kLargest (int arr[], int num, int k){
11+
12+ // build the min heap
13+ priority_queue<int , vector<int > , greater<int >> pq;
14+
15+ // bulid the heap for k elem
16+ for (int i = 0 ; i< k; i++){
17+ pq.push (arr[i]);
18+
19+ }
20+
21+ // go to the k+1 to the last
22+ for (int i = k; i< num ; i++){
23+ if (pq.top () > arr[i]){
24+ continue ;
25+ }
26+ else {
27+ pq.pop ();
28+ pq.push (arr[i]);
29+ }
30+ }
31+
32+ // print the elements of the min heap
33+ while (pq.empty () == false ){
34+ cout << pq.top ()<<" " ;
35+ pq.pop ();
36+ }
37+
38+ }
39+
40+ int main (){
41+ int num;
42+ cin >> num;
43+ int arr[num];
44+ for (int i = 0 ; i< num; i++){
45+ cin >> arr[i];
46+ }
47+ int k;
48+ cin >>k;
49+ kLargest (arr, num, k);
50+ return 0 ;
51+
52+ }
You can’t perform that action at this time.
0 commit comments