Challenge: Find k Largest Elements in the Array
If you are given an array and any number "k", can you write a code to find the first "k" largest elements using Max-Heap?
We'll cover the following
Problem Statement
Implement a function findKLargest(int arr[], int size, int k)
that takes an unsorted integer array as input and returns the largest elements in the array using a Max Heap. The maxHeap
class is prepended in this exercise, so feel free to use it! Have a look at the illustration given for a clearer picture of the problem.
Output:
Returns integer vector containing first k largest elements from arr
Sample Input
array = {9,4,7,1,-2,6,5} k = 3
Sample Output
[9,7,6]
Explanation
As “k” is 3, so we need to find the top 3 maximum elements from given array. 9 is the largest value in the array, while 7 is the second maximum, and 6 is the third max.
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.