K largest elements | Practice | GeeksforGeeks

Given an array of N positive integers, print k largest elements from the array. 
Example 1:
Input:
N = 5, k = 2
arr[] = {12,5,787,1,23}
Output: 787 23
Explanation: First largest element in
the array is 787 and the second largest
is 23.

Example 2:
Input:
N = 7, k = 3
arr[] = {1,23,12,9,30,2,50}
Output: 50 30 23
Explanation: Three Largest element in
the array are 50, 30 and 23.
Your Task:
Complete the function kLargest() that takes the array, N and K as input parameters and returns a list of k largest element in descending order. 
Expected Time Complexity: O(N log K)
Expected Auxiliary Space: O(K)
Constraints:
1 ≤ N ≤ 104
K ≤ N
1 ≤ array[i] ≤ 105
0
adityasuhane47 hours ago
vector<int> kLargest(int arr[], int n, int k)
   {
       vector<int> v;
       sort(arr,arr+n,greater<int>());
       for (int i = 0; i < k; i++)
       {
           v.push_back(arr[i]);
       }
       return v;
       
   }
0
gupta2411sumit2 days ago
 vector<int> kLargest(int arr[], int n, int k)   {       // code here       vector<int>ans ;       priority_queue<int>pq ;              for( int i = 0 ; i< n ; i++ )       {           pq.push(arr[i]) ;       }              for( int i = 0 ; i<k ; i++)       {           ans.push_back(pq.top()) ;           pq.pop() ;       }               return ans ;   }
0
dpahariya14 days ago
li.sort()
li.reverse()
return li[:k]
0
ashishbutola75 days ago
Javascript solution with Maxheap -: 
kLargest(arr,n,k)   {       let maxHeap = []       let removed = []       const heapifyUp = () => {           let childIndex = (maxHeap.length - 1)           let parentIndex = Math.floor((childIndex - 1)/2)           if (!childIndex) return           while(maxHeap[parentIndex] && (maxHeap[parentIndex] < maxHeap[childIndex])) {               const temp = maxHeap[parentIndex]               maxHeap[parentIndex] = maxHeap[childIndex]               maxHeap[childIndex] = temp               childIndex = parentIndex               parentIndex = Math.floor((childIndex - 1)/2)           }       }
       const heapifyDown = () => {           let parentIndex = 0           let leftChild = (2*parentIndex + 1)           let rightChild = (2*parentIndex + 2)           let maxIndex = parentIndex           while(maxHeap[leftChild]) {               if (maxHeap[parentIndex] < maxHeap[leftChild]) {                   maxIndex = leftChild               }
               if (maxHeap[rightChild] && (maxHeap[maxIndex] < maxHeap[rightChild])) {                   maxIndex = rightChild               }
               if (parentIndex === maxIndex) return
               const temp = maxHeap[parentIndex]               maxHeap[parentIndex] = maxHeap[maxIndex]               maxHeap[maxIndex] = temp
               parentIndex = maxIndex
               leftChild = (2*parentIndex + 1)               rightChild = (2*parentIndex + 2)                        }       }
       for (let i = 0; i < n; i++) {           maxHeap.push(arr[i])           heapifyUp()       }
       for (let i = 0; i < k; i++) {           const topElement = maxHeap[0]           const lastElem = maxHeap[maxHeap.length - 1]           maxHeap.pop()           maxHeap[0] = lastElem           heapifyDown()           removed.push(topElement)       }
       return removed   }
+1
beast_bhavesh1 week ago
using min heap 
{       // code here       priority_queue< int,vector<int>,greater<int> >pq;        vector<int>ans;       for(int i=0;i<n;i++){               pq.push(arr[i]);               if(pq.size() > k){                   pq.pop();               }       }       while(pq.empty() == false){           ans.push_back(pq.top());              pq.pop();       }       reverse(ans.begin(), ans.end());       return ans;   }
+2
sudhanshushekhar15582 weeks ago
prog.java:57: error: incompatible types: Integer cannot be converted to ArrayList<Integer> return largest.peek(); ^
//Initial Template for Java

import java.util.*;
import java.io.*;


class Main
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        int t = sc.nextInt();
        
        while(t > 0)
        {
            int n = sc.nextInt();
            int k = sc.nextInt();
            
            int arr[] = new int[n];
            for(int i = 0; i<n; ++i)
                arr[i] = sc.nextInt();
            Solution ob = new Solution();
            ArrayList<Integer> list = ob.kLargest(arr, n, k);
            for(int i = 0; i<list.size(); i++)
                System.out.print(list.get(i) + " ");
            System.out.println();
            t--;
        }
    }
}


// } Driver Code Ends


//User function Template for Java

class Solution
{
    //Function to return k largest elements from an array.
    public static ArrayList<Integer> kLargest(int arr[], int n, int k)
    {
        PriorityQueue<Integer>largest = new PriorityQueue<>();
        for (int i=0 ;i<=k-1;i++)
        {
            largest.add(arr[i]);
        }
        for(int i=k ; i<n-1;i++)
        {
            if(largest.peek() < arr[i])
            {
                largest.remove();
                largest.add(arr[i]);
            }
        }
        return largest.peek();
        
    }
}
-3
kumarr32033 weeks ago
 //c++ solution
 
   vector<int> kLargest(int a[], int n, int k)   {       // code here       vector<int>v;       sort(a,a+n);       for(int i=n-1;i>=n-k;i--)       {           v.push_back(a[i]);       }       return v;   }};
0
shivamtech20241 month ago
 vector<int> kLargest(int arr[], int n, int k)      {       // code here                     vector<int> vec;       stack<int> st;                      priority_queue< int , vector<int> , greater<int> > pq;                            for(int i=0;i<k;i++){           pq.push(arr[i]);       }                                   for(int i=k;i<n;i++){           if(arr[i] > pq.top()){                              pq.pop();               pq.push(arr[i]);                          }       }                                                               for(int i=0;i<k;i++){                               int ans = pq.top();                    st.push(ans);               pq.pop();           }                                    for(int i=0;i<k;i++){               vec.push_back(st.top());               st.pop();           }             return vec;                          }
+1
mbi20210121 month ago
vector<int> kLargest(int arr[], int n, int k)   {       priority_queue<int,vector<int>,greater<int>>minh;              for(int i=0;i<n;i++)       {           minh.push(arr[i]);           if(minh.size()>k)           {               minh.pop();           }       }              vector<int>ans(k,0);       while(k>0)       {           ans[k-1]=minh.top();           minh.pop();           k--;       }       return ans;   }
0
tusharkhatriofficial1 month ago
Python Solution
#User function Template for python3

class Solution:
    #Function to return k largest elements from an array.
    def kLargest(self,li,n,k):
        # code here
        li.sort(reverse=True)
        return li[:k]
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested 
                                    against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code.
                                    On submission, your code is tested against multiple test cases consisting of all
                                        possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as
                                        the final solution code.
You can view the solutions submitted by other users from the submission tab.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested 
                                against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems does not guarantee the 
                                correctness of code. On submission, your code is tested against multiple test cases
                                    consisting of all possible corner cases and stress constraints.