↓Skip to main content
  1. LeetCode/

LeetCode 3684: Maximize Sum of At Most K Distinct Elements

·1 min· ·
LeetCode Easy Greedy Sorting Hash-Table
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2026-01-29

  • Submissions: Wrong Answer → Accepted

Approach
#

Every value is positive, so taking more is better; take up to k. They must be distinct, so deduplicate and take the k largest. With fewer than k distinct values, take them all.

My Attempts
#

Attempt 1 hard-coded “the top 3” from the examples with biggest, second, third, never using k. For nums = [5, 3], k = 1 the answer is [5]; it returned [5, 3].

Sorting descending, skipping duplicates, and stopping at k passed.

Solution
#

class Solution:
    def maxKDistinct(self, nums: List[int], k: int) -> List[int]:
        return sorted(set(nums), reverse=True)[:k]

Complexity
#

Time O(n log n), space O(n).

Mistakes to Avoid
#

  • Do not hard-code the k from the examples; use the parameter.

Interview Explanation
#

All values are positive, so more is better. I deduplicate, sort descending, and take the first k. Time O(n log n).

Related

LeetCode 2357: Make Array Zero by Subtracting Equal Amounts
·1 min
LeetCode Easy Array Hash-Table Greedy Sorting
LeetCode 2357 note: each operation zeroes the group of the smallest positive value, so the answer is the number of distinct positive values
LeetCode 3545: Minimum Deletions for At Most K Distinct Characters
·1 min
LeetCode Easy Greedy Hash-Table String Sorting Counting
LeetCode 3545 note: reducing the number of kinds means deleting whole kinds, starting from the least frequent
LeetCode 976: Largest Perimeter Triangle
·2 mins
LeetCode Easy Math Greedy Sorting Geometry Array
LeetCode 976 note: after sorting, check consecutive triples from the largest down; the first with a + b > c gives the largest perimeter
LeetCode 3606: Coupon Code Validator
·2 mins
LeetCode Easy Hash-Table String Sorting
LeetCode 3606 note: filter valid coupons, then sort by (category order, code); character ranges must include z, Z and 9
LeetCode 3487: Maximum Unique Subarray Sum After Deletion
·2 mins
LeetCode Easy Greedy Hash-Table Array
LeetCode 3487 note: free deletion means picking distinct values; take every non-negative one, or only the maximum when all are negative
LeetCode 3074: Apple Redistribution into Boxes
·1 min
LeetCode Easy Array Greedy Sorting
LeetCode 3074 note: apples can be split freely, so take boxes from the largest capacity until the total fits every apple