Find Subsequence of Length K With the Largest Sum

easy array sorting

Problem

Given an array nums and integer k, find any subsequence of length k that has the largest possible sum. Return that subsequence (in any order that preserves a valid subsequence).

Inputnums = [2,1,3,3], k = 2
Output[3,3]
The two 3's give the largest sum 6.

def max_subsequence(nums, k):
    idx = sorted(range(len(nums)), key=lambda i: nums[i], reverse=True)
    chosen = sorted(idx[:k])
    return [nums[i] for i in chosen]
function maxSubsequence(nums, k) {
  const idx = nums.map((v, i) => i);
  idx.sort((a, b) => nums[b] - nums[a]);
  const chosen = idx.slice(0, k).sort((a, b) => a - b);
  return chosen.map(i => nums[i]);
}
class Solution {
    public int[] maxSubsequence(int[] nums, int k) {
        Integer[] idx = new Integer[nums.length];
        for (int i = 0; i < nums.length; i++) idx[i] = i;
        Arrays.sort(idx, (a, b) -> nums[b] - nums[a]);
        int[] chosen = new int[k];
        for (int i = 0; i < k; i++) chosen[i] = idx[i];
        Arrays.sort(chosen);
        int[] res = new int[k];
        for (int i = 0; i < k; i++) res[i] = nums[chosen[i]];
        return res;
    }
}
vector<int> maxSubsequence(vector<int>& nums, int k) {
    vector<int> idx(nums.size());
    iota(idx.begin(), idx.end(), 0);
    sort(idx.begin(), idx.end(), [&](int a, int b){ return nums[a] > nums[b]; });
    vector<int> chosen(idx.begin(), idx.begin() + k);
    sort(chosen.begin(), chosen.end());
    vector<int> res;
    for (int i : chosen) res.push_back(nums[i]);
    return res;
}
Time: O(n log n) Space: O(n)