[LeetCode] Maximize Sum of At Most K Distinct Elements

3684. Maximize Sum of At Most K Distinct Elements

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.

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
vector<int> maxKDistinct(vector<int>& nums, int k) {
sort(begin(nums), end(nums));
nums.erase(unique(begin(nums), end(nums)), end(nums));
reverse(begin(nums), end(nums));
while(nums.size() > k) nums.pop_back();
return nums;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2025/09/19/PS/LeetCode/maximize-sum-of-at-most-k-distinct-elements/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.