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.

 

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
  • -105 <= nums[i] <= 105
  • 1 <= k <= nums.length

2099. Find Subsequence of Length K With the Largest Sum
struct Solution;

#[derive(Clone)]
struct Pair {
    value: i32,
    index: usize,
}

impl Solution {
    fn max_subsequence(nums: Vec<i32>, k: i32) -> Vec<i32> {
        let n = nums.len();
        let mut pairs: Vec<Pair> = vec![];
        for i in 0..n {
            pairs.push(Pair {
                value: nums[i],
                index: i,
            });
        }
        pairs.sort_by_key(|p| p.value);
        let k = k as usize;
        let mut k_pairs: Vec<Pair> = vec![];
        for i in 0..k {
            k_pairs.push(pairs[n - k + i].clone());
        }
        k_pairs.sort_by_key(|p| p.index);
        let mut res = vec![];
        for i in 0..k {
            res.push(k_pairs[i].value);
        }
        res
    }
}

#[test]
fn test() {
    let nums = vec![2, 1, 3, 3];
    let k = 2;
    let res = vec![3, 3];
    assert_eq!(Solution::max_subsequence(nums, k), res);
    let nums = vec![-1, -2, 3, 4];
    let k = 3;
    let res = vec![-1, 3, 4];
    assert_eq!(Solution::max_subsequence(nums, k), res);
    let nums = vec![3, 4, 3, 3];
    let k = 2;
    let res = vec![4, 3];
    assert_eq!(Solution::max_subsequence(nums, k), res);
}