Find Subsequence of Length K with the Largest Sum

Pick the k largest values then output them in original-order.

Easy
Time O(n log k) Space O(k)
LeetCode
5 min read
top-k heaps

Problem#

Return a length-k subsequence of nums with the maximum sum. Order of elements in the result follows the input.

Examples#

  • nums = [2,1,3,3], k = 2[3,3]
  • nums = [-1,-2,3,4], k = 3[-1,3,4]

Constraints#

  • 1 <= k <= nums.length <= 1000.

Approach#

Min-heap of (value, index) size k — keeps the k largest values along with their indices. After processing, sort the kept entries by index to restore input order.

Solution#

Top-K Subsequence
class Solution {
public:
vector<int> maxSubsequence(vector<int>& nums, int k) {
priority_queue<pair<int,int>, vector<pair<int,int>>, greater<>> pq;
for (int i = 0; i < (int)nums.size(); ++i) {
pq.push({nums[i], i});
if ((int)pq.size() > k) pq.pop();
}
vector<pair<int,int>> kept;
while (!pq.empty()) { kept.push_back(pq.top()); pq.pop(); }
sort(kept.begin(), kept.end(), [](auto& a, auto& b){ return a.second < b.second; });
vector<int> ans;
for (auto& [v, _] : kept) ans.push_back(v);
return ans;
}
};

Editorial#

Two stages: (a) pick the k largest (heap), (b) restore input order (sort by index). Tracking the index in the heap entry is essential — without it, ordering the result would require scanning the input again.

Complexity#

  • Time: O(n log k).
  • Space: O(k).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.