2099: Find-Subsequence-of-Length-K-With-the-Largest-Sum
Easy
table of contents
Basically, we just want to find the k
largest values of nums
and return them in
their original order.
We can do this by:
pairing each value in
nums
with its respective index,pairedNums
sort the array
pairedNums
and extract thek
largest valuesthen, simply extract the indices and place the respective values back into an
ans
array
code
class Solution {
public:
<int> maxSubsequence(vector<int>& nums, int k) {
vector<pair<int, int>> pairedNums;
vectorfor (int i = 0; i < nums.size(); ++i) {
.push_back({nums[i], i});
pairedNums}
(pairedNums.begin(), pairedNums.end(), greater());
sort
<int> indices;
vector<int> ans;
vectorfor (int i = 0; i < k; ++i) {
.push_back(pairedNums[i].second);
indices}
(indices.begin(), indices.end());
sortfor (int i = 0; i < indices.size(); ++i) {
.push_back(nums[indices[i]]);
ans}
return ans;
}
};