Skip to main content

Maximize Sum of At Most K Distinct Elements - Solution & Explanation

Practice this problem

Problem Statement

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.

 

Example 1:

Input: nums = [84,93,100,77,90], k = 3

Output: [100,93,90]

Explanation:

The maximum sum is 283, which is attained by choosing 93, 100 and 90. We rearrange them in strictly descending order as [100, 93, 90].

Example 2:

Input: nums = [84,93,100,77,93], k = 3

Output: [100,93,84]

Explanation:

The maximum sum is 277, which is attained by choosing 84, 93 and 100. We rearrange them in strictly descending order as [100, 93, 84]. We cannot choose 93, 100 and 93 because the chosen numbers must be distinct.

Example 3:

Input: nums = [1,1,1,2,2,2], k = 6

Output: [2,1]

Explanation:

The maximum sum is 3, which is attained by choosing 1 and 2. We rearrange them in strictly descending order as [2, 1].

 

Constraints:

  • 1 <= nums.length <= 100
  • 1 <= nums[i] <= 109
  • 1 <= k <= nums.length

Approach Overview

Problem Overview: You are given an array of integers and a number k. The goal is to select at most k distinct elements such that their sum is as large as possible. Duplicate values cannot be counted multiple times, so the solution must ensure uniqueness while maximizing the total.

Approach 1: Brute Force with Distinct Tracking (Exponential Time)

The most direct idea is to try every possible subset of elements and keep only those containing at most k distinct values. For each valid subset, compute the sum and track the maximum. While this guarantees correctness, the number of subsets grows exponentially with the array size. Time complexity becomes O(2^n) and space complexity is O(n) due to recursion or subset storage. This approach is mainly useful for understanding the constraints but is impractical for real input sizes.

Approach 2: Hash Set + Sorting (Greedy) (O(n log n))

The key observation is that if you want the maximum possible sum with distinct elements, you should always choose the largest available unique values first. Start by removing duplicates using a hash set. This guarantees each number is counted once. Convert the set back to a list and sort it in descending order using a standard sorting algorithm. Then iterate through the sorted values and add the top k elements to the sum. The sorting step dominates the complexity, giving O(n log n) time and O(n) space.

This approach combines ideas from array processing and hash table deduplication. The greedy step works because larger numbers always contribute more to the final sum, so selecting the largest unique values first is optimal.

Approach 3: Hash Set + Max Heap (O(n log n))

Another option is to insert distinct values into a max heap instead of sorting the entire array. After removing duplicates using a hash set, push the numbers into a heap and extract the largest element up to k times. Heap insertion and extraction both take O(log n), producing overall time complexity O(n log n) and space complexity O(n). This technique is useful when the data stream arrives incrementally or when you prefer priority queue operations instead of full sorting.

The greedy reasoning remains the same: always take the largest available distinct value first. This aligns with typical patterns seen in greedy optimization and sorting-based selection problems.

Recommended for interviews: The hash set + sorting approach is the most expected solution. It clearly demonstrates two key skills: eliminating duplicates efficiently and applying a greedy selection strategy after sorting. Mentioning the brute force method shows you understand the search space, but implementing the sorting-based approach proves you can reduce the problem to a clean O(n log n) solution.

Solution

We first sort the array nums, then iterate from the end to the beginning, selecting the largest k distinct elements. Since we require a strictly decreasing order, we skip duplicate elements during selection.

The time complexity is O(n times log n), where n is the length of the nums array. Ignoring the space used for the answer, the space complexity is O(log n).

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force Subset EnumerationO(2^n)O(n)Conceptual understanding or very small input sizes
Hash Set + Sorting (Greedy)O(n log n)O(n)General case; simple and interview-friendly solution
Hash Set + Max HeapO(n log n)O(n)Useful when extracting top elements incrementally instead of sorting

Video Solution

3684. Maximize Sum of At Most K Distinct Elements (Leetcode Easy) • Programming Live with Larry • 346 views views

Watch 7 more video solutions →

Frequently Asked Questions

Is Maximize Sum of At Most K Distinct Elements easy or hard?
This problem is generally classified as Easy because the key insight is straightforward: remove duplicates and pick the largest values. Once you recognize the greedy pattern, the implementation using sorting or a heap is simple and efficient.
Maximize Sum of At Most K Distinct Elements Python/Java solution
The typical implementation converts the array to a set to remove duplicates, sorts the unique values in descending order, and sums the first k numbers. The same logic works across Python, Java, C++, Go, and TypeScript with minor syntax differences.
How to solve Maximize Sum of At Most K Distinct Elements in O(n)?
A strict O(n) solution is generally not achievable if sorting is required to identify the largest values. However, you can approach near-linear performance by deduplicating with a hash set in O(n) and then selecting the largest elements using a selection algorithm or heap. Most implementations still rely on sorting with O(n log n) complexity.
What is the best approach for Maximize Sum of At Most K Distinct Elements?
The most practical approach uses a hash set to remove duplicates and sorting to select the largest values. After deduplication, sort the numbers in descending order and sum the top k values. This greedy strategy ensures the maximum sum and runs in O(n log n) time with O(n) space.
Is Maximize Sum of At Most K Distinct Elements asked at Google/Amazon/Meta?
Problems combining arrays, hash tables, and greedy selection frequently appear in interviews at companies like Amazon and Google. Variations of selecting the top k unique elements or maximizing sums with constraints are common patterns used to evaluate problem-solving and data structure knowledge.
What data structure is used in Maximize Sum of At Most K Distinct Elements?
The primary data structure is a hash set to enforce distinct values. After deduplication, either sorting or a max heap is used to retrieve the largest elements efficiently. These structures work together to guarantee both uniqueness and optimal selection.
What is the time complexity of Maximize Sum of At Most K Distinct Elements?
The optimal solution runs in O(n log n) time because of the sorting step. Removing duplicates using a hash set takes O(n), and selecting the top k elements takes O(k). Space complexity is O(n) to store the unique values.

Ready to solve this problem?

Practice Maximize Sum of At Most K Distinct Elements with our built-in code editor and test cases.

Practice on FleetCode