Challenge: Find k Largest Elements in the List
If you are given a list and any number "k", can you write a code to find the first "k" largest elements using a Max-Heap?
We'll cover the following
Problem Statement
Implement a function findKLargest(lst,k)
that takes an unsorted integer list as input and returns the largest elements in the list using a Max Heap. The maxHeap
class that was written in Max Heap (Implementation) 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. Implement a function findKlargest()
which takes a list as input and finds the “k” largest elements in the list using a Max-Heap. An illustration is also provided for your understanding.
Output:
Returns integer list containing first k largest elements from my_list
Sample Input
lst = [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 the given list. 9 is the largest value in the list, 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.