Skip to content

Commit 2d001f0

Browse files
parmeet9891abranhe
authored andcommitted
Add files via upload
1 parent c99ee6b commit 2d001f0

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
#include<bits/stdc++.h>
2+
using namespace std;
3+
4+
/*
5+
6+
Given an array A of random integers and an integer k, find and return the kth largest element in the array.
7+
8+
*/
9+
10+
int kthLargest (vector<int> arr, int n, int k){
11+
12+
priority_queue<int, vector<int>, greater<int>> pq;
13+
14+
for(int i = 0; i < k; i++) {
15+
pq.push(arr[i]);
16+
}
17+
18+
for(int i = k; i < n; i++) {
19+
int val = pq.top();
20+
if(arr[i] > val) {
21+
pq.pop();
22+
pq.push(arr[i]);
23+
}
24+
}
25+
26+
return pq.top();
27+
28+
}
29+
30+
int main() {
31+
int n, k, s;
32+
vector<int> arr;
33+
cin >> n;
34+
35+
for (int i = 0; i < n; i++) {
36+
cin >> s;
37+
arr.push_back(s);
38+
}
39+
40+
cin >> k;
41+
cout << kthLargest(arr, n, k) << endl;
42+
}
43+
44+

0 commit comments

Comments
 (0)