Challenge: Find k Largest Elements in an 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(arr,k)
that takes an unsorted integer array as input and returns the largest elements in the array using a max heap. The maxHeap
class that was written in a 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.
Input
An array containing integers
Output
Returns an integer array containing first k largest elements
Sample Input
arr = [9,4,7,1,-2,6,5] k = 3
Sample Output
[9,7,6]
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.