K largest Elements Geeks For Geeks

 class Solution

{

    //Function to return k largest elements from an array.

    public static ArrayList<Integer> kLargest(int arr[], int n, int k)

    {

        PriorityQueue <Integer> p=new PriorityQueue<Integer>();

for(int i=0;i<k;i++){

p.add(arr[i]);

}

for(int i=k;i<n;i++){

if(p.peek()<arr[i]){

p.remove();

p.add(arr[i]);

}

}

ArrayList<Integer> aa=new ArrayList<Integer>();

aa.addAll(p);

Collections.sort(aa,Collections.reverseOrder());

return aa;

    }

}


Using Priority Queue

Time: O(NLOGK) [Sorting of K elements list] [GFG Time : 3.6/6.8]

Space: O(K) [Using ArrayList additionally of size k]

{Here we will be adding the first k elements in the priority queue. Then for the next (n-k) elements, we will compare with the peek element of the queue. If the peek element is small then we will remove it from the queue and add the element from an array, and if the peek element is large or equal we will do nothing except iteration further. Priority queue always has a peek of an element with high priority (for numbers standard is low value has high priority). After getting all the highest numbers we will print them out after sorting them in reverse order. If we print without reverse sorting then the elements will be output in an unsorted fashion as high priority elements with low value will come first.}

Thanks for Reading.

"Knowledge enhances by Sharing not by saving."

Please like, share, and comment.


Comments

Popular posts from this blog

Solutions Of Practice Questions Dated 01-06-2022

CODEFORCES SPY DETECTED ROUND 713

Maximum Winning Score Geeks For Geeks