Simple solution in c++ using stl algorithm


#1

vector Solution::solve(vector &A, int B) {
vectorres;
sort(A.begin(),A.end());
for(int i=A.size()-1;res.size()<B;i–){
res.push_back(A[i]);
}
return res;
}


#2

Decent solution but can be improved.Always try to use the data structure(here at IB) whose questions you are trying to do. Think why heap(or priority queue) will work better here.
vector Solution::solve(vector &A, int B) {
if(B>=A.size()) return A;
priority_queuepq;
for(int i=0;i<A.size();i++){
pq.push(A[i]);
}
vectorsol(B);
for(int i=0;i<B;i++){
sol[i]=pq.top();
pq.pop();
}
return sol;
}