LeetCode solutions

3997. Maximize Sum of At Most K Distinct Elements

My accepted Python solution to LeetCode problem 3997, Maximize Sum of At Most K Distinct Elements, running in 0ms.

  • Difficulty: Easy
  • Python
  • Runtime 0ms
  • Memory 17.1MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 0ms, memory 17.1MB, accepted 2025-12-30.

python
class Solution:
    def maxKDistinct(self, nums: List[int], k: int) -> List[int]:
        # Get unique elements and sort in descending order
        unique = sorted(set(nums), reverse=True)
        # Take at most k elements
        return unique[:k]

Source