Skip to content

Commit 0aadd0a

Browse files
committed
k largest elements
1 parent 5dd3e6e commit 0aadd0a

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

DSA Crack Sheet/README.md

+2
Original file line numberDiff line numberDiff line change
@@ -284,6 +284,8 @@
284284

285285
- [Building Heap from Array](https://www.geeksforgeeks.org/building-heap-from-array/ "view post")
286286
- [Heap Sort](https://practice.geeksforgeeks.org/problems/heap-sort/1# "view question") - [Cpp Solution](./solutions/Heap%20Sort.cpp)
287+
- [Maximum of all subarrays of size k](https://practice.geeksforgeeks.org/problems/maximum-of-all-subarrays-of-size-k3101/1# "view question") - [Cpp Solution](./solutions/Maximum%20of%20all%20subarrays%20of%20size%20k.cpp)
288+
- [k largest elements](https://practice.geeksforgeeks.org/problems/k-largest-elements4206/1# "view question") - [Cpp Solution](./solutions/k%20largest%20elements.cpp)
287289
- []( "view question") - [Cpp Solution](./solutions/.cpp)
288290

289291
### Graphs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/*
2+
k largest elements
3+
==================
4+
5+
Given an array Arr of N positive integers, find K largest elements from the array. The output elements should be printed in decreasing order.
6+
7+
Example 1:
8+
Input:
9+
N = 5, K = 2
10+
Arr[] = {12, 5, 787, 1, 23}
11+
Output: 787 23
12+
Explanation: 1st largest element in the
13+
array is 787 and second largest is 23.
14+
15+
Example 2:
16+
Input:
17+
N = 7, K = 3
18+
Arr[] = {1, 23, 12, 9, 30, 2, 50}
19+
Output: 50 30 23
20+
Explanation: 3 Largest element in the
21+
array are 50, 30 and 23.
22+
Your Task:
23+
You don't need to read input or print anything. Your task is to complete the function kLargest() which takes the array of integers arr, n and k as parameters and returns an array of integers denoting the answer. The array should be in decreasing order.
24+
25+
Expected Time Complexity: O(N)
26+
Expected Auxiliary Space: O(K*logK)
27+
28+
Constraints:
29+
1 ≤ K ≤ N ≤ 105
30+
1 ≤ Arr[i] ≤ 106
31+
32+
*/
33+
34+
vector<int> kLargest(int arr[], int n, int k)
35+
{
36+
vector<int> ans;
37+
priority_queue<int> pq;
38+
for (int i = 0; i < n; ++i)
39+
pq.push(arr[i]);
40+
41+
for (int i = 0; i < k; ++i)
42+
{
43+
ans.push_back(pq.top());
44+
pq.pop();
45+
}
46+
47+
return ans;
48+
}

0 commit comments

Comments
 (0)