#3684

Maximize Sum of At Most K Distinct Elements

Easy
ArrayHash TableGreedySortingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

Use a set to remove duplicates, sort the distinct elements, and select the top k elements for maximum sum.

⚙️

Algorithm

3 steps
  1. 1Step 1: Convert nums to a set to remove duplicates.
  2. 2Step 2: Sort the distinct elements in descending order.
  3. 3Step 3: Return the first k elements from the sorted list.
solution.py3 lines
1def maxSumKDistinct(nums, k):
2    distinct = sorted(set(nums), reverse=True)
3    return distinct[:k]

Complexity note: Sorting the distinct elements dominates the time complexity, while space is used for the set.

  • 1Using a set efficiently handles duplicates.
  • 2Sorting allows easy selection of the largest elements.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.