Code : K largest elements
Line 1 : Size of array (n)
Line 2 : Array elements (separated by space)
Line 3 : Integer k
k largest elements
13
2 12 9 16 10 5 3 20 25 11 1 8 6
4
12
16
20
25
#include<bits/stdc++.h>vector<int> kLargest(int input[], int n, int k){ /* Don't write main(). * Don't read input, it is passed as function argument. * Return output and don't print it. * Taking input and printing output is handled automatically. */priority_queue<int>maxh;for(int i=0;i<n;i++){ maxh.push(input[i]); }vector<int>ans;for(int i=0;i<k;i++){ ans.push_back(maxh.top()); maxh.pop();}reverse(ans.begin(),ans.end());return ans;}
Comments
Post a Comment