Find Subsequence of Length K With the Largest Sum
EasyUpdated: Aug 2, 2025
Practice on:
Problem
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.
Examples
Example 1
Input: nums = [2,1,3,3], k = 2
Output: [3,3]
Explanation:
The subsequence has the largest sum of 3 + 3 = 6.
Example 2
Input: nums = [-1,-2,3,4], k = 3
Output: [-1,3,4]
Explanation:
The subsequence has the largest sum of -1 + 3 + 4 = 6.
Example 3
Input: nums = [3,4,3,3], k = 2
Output: [3,4]
Explanation:
The subsequence has the largest sum of 3 + 4 = 7.
Another possible subsequence is [4, 3].
Constraints
1 <= nums.length <= 1000-10^5 <= nums[i] <= 10^51 <= k <= nums.length
Solution
Method 1 – Heap & Index Tracking
Intuition
To get the largest sum subsequence of length k, we need the k largest elements from nums, but we must preserve their original order. By selecting the k largest elements (with their indices), sorting those indices, and then extracting the values in order, we ensure both maximal sum and correct subsequence order.
Approach
- Pair each element in
numswith its index. - Sort these pairs by value in descending order.
- Select the first
kpairs (the largestkelements). - Extract their indices and sort them to maintain the original order.
- Build the answer by picking elements from
numsat these sorted indices.
Code
C++
class Solution {
public:
vector<int> maxSubsequence(vector<int>& nums, int k) {
vector<pair<int, int>> v;
for (int i = 0; i < nums.size(); ++i)
v.push_back({nums[i], i});
sort(v.rbegin(), v.rend());
vector<int> idx;
for (int i = 0; i < k; ++i)
idx.push_back(v[i].second);
sort(idx.begin(), idx.end());
vector<int> ans;
for (int i : idx)
ans.push_back(nums[i]);
return ans;
}
};
Go
func maxSubsequence(nums []int, k int) []int {
type pair struct{ val, idx int }
v := make([]pair, len(nums))
for i, num := range nums {
v[i] = pair{num, i}
}
sort.Slice(v, func(i, j int) bool {
return v[i].val > v[j].val
})
idx := make([]int, k)
for i := 0; i < k; i++ {
idx[i] = v[i].idx
}
sort.Ints(idx)
ans := make([]int, k)
for i, id := range idx {
ans[i] = nums[id]
}
return ans
}
Java
class Solution {
public int[] maxSubsequence(int[] nums, int k) {
int n = nums.length;
int[][] v = new int[n][2];
for (int i = 0; i < n; i++) {
v[i][0] = nums[i];
v[i][1] = i;
}
Arrays.sort(v, (a, b) -> b[0] - a[0]);
int[] idx = new int[k];
for (int i = 0; i < k; i++) {
idx[i] = v[i][1];
}
Arrays.sort(idx);
int[] ans = new int[k];
for (int i = 0; i < k; i++) {
ans[i] = nums[idx[i]];
}
return ans;
}
}
Kotlin
class Solution {
fun maxSubsequence(nums: IntArray, k: Int): IntArray {
val v = nums.mapIndexed { i, num -> Pair(num, i) }
.sortedByDescending { it.first }
val idx = v.take(k).map { it.second }.sorted()
return idx.map { nums[it] }.toIntArray()
}
}
Python
class Solution:
def maxSubsequence(self, nums: list[int], k: int) -> list[int]:
v = sorted([(num, i) for i, num in enumerate(nums)], reverse=True)
idx = sorted([i for _, i in v[:k]])
return [nums[i] for i in idx]
Rust
impl Solution {
pub fn max_subsequence(nums: Vec<i32>, k: i32) -> Vec<i32> {
let mut v: Vec<(i32, usize)> = nums.iter().cloned().zip(0..).collect();
v.sort_by(|a, b| b.0.cmp(&a.0));
let mut idx: Vec<usize> = v.iter().take(k as usize).map(|&(_, i)| i).collect();
idx.sort();
idx.iter().map(|&i| nums[i]).collect()
}
}
Complexity
- ⏰ Time complexity:
O(n log n)(for sorting) - 🧺 Space complexity:
O(n)(for storing pairs and indices)