[LeetCode] Find Subsequence of Length K With the Largest Sum

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
vector<int> maxSubsequence(vector<int>& nums, int k) {
int n = nums.size();
vector<int> ord(n);
iota(begin(ord), end(ord), 0);
sort(begin(ord), end(ord), [&](int i, int j) {
return nums[i] > nums[j];
});
sort(begin(ord), begin(ord) + k);
vector<int> res;
for(int i = 0; i < k; i++) res.push_back(nums[ord[i]]);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/06/28/PS/LeetCode/find-subsequence-of-length-k-with-the-largest-sum/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.