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.
classSolution {
publicint[]maxSubsequence(int[] nums, int k) {
int n = nums.length;
int[][] v =newint[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 =newint[k];
for (int i = 0; i < k; i++) {
idx[i]= v[i][1];
}
Arrays.sort(idx);
int[] ans =newint[k];
for (int i = 0; i < k; i++) {
ans[i]= nums[idx[i]];
}
return ans;
}
}
1
2
3
4
5
6
7
8
classSolution {
funmaxSubsequence(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()
}
}
1
2
3
4
5
classSolution:
defmaxSubsequence(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]