#3684
Easy Algorithms Maximize sum of at most k distinct elements
Array Hash Table Greedy Sorting
76.6% acceptance
Feb 25, 2026
53
4
You are given a positive integer array nums and an integer k.
Choose at most k elements from nums so that their sum is maximized. However, the chosen numbers must be distinct.
Return an array containing the chosen numbers in strictly descending order.
Solution
Rust
Time O(n log n)
Space O(1)
impl Solution {
pub fn max_k_distinct(nums: Vec<i32>, k: i32) -> Vec<i32> {
use std::collections::BTreeSet;
let unique: BTreeSet<i32> = nums.into_iter().collect();
let result: Vec<i32> = unique.into_iter().rev().take(k as usize).collect();
result
}
}