Challenge 3: Finding “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?

Problem statement

Implement a function findKLargest(int[] arr, int size, int k) that takes an unsorted integer array as input and returns the kk largest elements in the array using a max heap. The maxHeap class is prepended in this exercise, so feel free to use it! Take a look at the illustration given for a clearer picture of the problem.

Input

This is an array, it’s size, and a number k.

Output

It returns an integer vector containing the first “k” largest elements from arr.

Sample input

array = {9,4,7,1,-2,6,5}    k = 3

Sample output

[9,7,6]

As “k” is 3, you need to find the top three maximum elements from the 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.