-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsubsequenceOfLength.txt
38 lines (29 loc) · 1.09 KB
/
subsequenceOfLength.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
2099. Find Subsequence of Length K With the Largest Sum
You are given an integer array nums and an integer k.
You want to find a subsequence of nums of length k that has the largest sum.
Return any such subsequence as an integer array of length k.
A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order
of the remaining elements.
class Solution {
public:
vector<int> maxSubsequence(vector<int>& nums, int k) {
priority_queue<pair<int,int> , vector<pair<int,int>>,greater<pair<int,int>> > pq;
for(int i = 0; i < nums.size(); i++){
pq.push({nums[i],i});
if(pq.size() > k){
pq.pop();
}
}
priority_queue<pair<int,int> , vector<pair<int,int>>,greater<pair<int,int>> > temp;
while(!pq.empty()){
temp.push({pq.top().second,pq.top().first});
pq.pop();
}
vector<int> ans;
while(!temp.empty()){
ans.push_back(temp.top().second);
temp.pop();
}
return ans;
}
};