Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Build confidence with an intuition-first walkthrough focused on array fundamentals.
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 <= 1001 <= nums[i] <= 1091 <= k <= nums.lengthProblem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map · Greedy
[84,93,100,77,90] 3
[84,93,100,77,93] 3
[1,1,1,2,2,2] 6
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3684: Maximize Sum of At Most K Distinct Elements
class Solution {
public int[] maxKDistinct(int[] nums, int k) {
Arrays.sort(nums);
int n = nums.length;
List<Integer> ans = new ArrayList<>();
for (int i = n - 1; i >= 0; --i) {
if (i + 1 < n && nums[i] == nums[i + 1]) {
continue;
}
ans.add(nums[i]);
if (--k == 0) {
break;
}
}
return ans.stream().mapToInt(x -> x).toArray();
}
}
// Accepted solution for LeetCode #3684: Maximize Sum of At Most K Distinct Elements
func maxKDistinct(nums []int, k int) (ans []int) {
slices.Sort(nums)
n := len(nums)
for i := n - 1; i >= 0; i-- {
if i+1 < n && nums[i] == nums[i+1] {
continue
}
ans = append(ans, nums[i])
if k--; k == 0 {
break
}
}
return
}
# Accepted solution for LeetCode #3684: Maximize Sum of At Most K Distinct Elements
class Solution:
def maxKDistinct(self, nums: List[int], k: int) -> List[int]:
nums.sort()
n = len(nums)
ans = []
for i in range(n - 1, -1, -1):
if i + 1 < n and nums[i] == nums[i + 1]:
continue
ans.append(nums[i])
k -= 1
if k == 0:
break
return ans
// Accepted solution for LeetCode #3684: Maximize Sum of At Most K Distinct Elements
fn max_k_distinct(nums: Vec<i32>, k: i32) -> Vec<i32> {
use std::collections::HashSet;
let k = k as usize;
let mut nums = nums;
nums.sort_unstable();
let mut ret = vec![];
let mut s = HashSet::new();
for n in nums.into_iter().rev() {
if s.contains(&n) {
continue;
}
ret.push(n);
s.insert(n);
if s.len() >= k {
break;
}
}
ret
}
fn main() {
let nums = vec![84, 93, 100, 77, 93];
let ret = max_k_distinct(nums, 3);
println!("ret={ret:?}");
}
#[test]
fn test() {
{
let nums = vec![84, 93, 100, 77, 90];
let ret = max_k_distinct(nums, 3);
assert_eq!(ret, vec![100, 93, 90]);
}
{
let nums = vec![84, 93, 100, 77, 93];
let ret = max_k_distinct(nums, 3);
assert_eq!(ret, vec![100, 93, 84]);
}
{
let nums = vec![1, 1, 1, 2, 2, 2];
let ret = max_k_distinct(nums, 6);
assert_eq!(ret, vec![2, 1]);
}
}
// Accepted solution for LeetCode #3684: Maximize Sum of At Most K Distinct Elements
function maxKDistinct(nums: number[], k: number): number[] {
nums.sort((a, b) => a - b);
const ans: number[] = [];
const n = nums.length;
for (let i = n - 1; ~i; --i) {
if (i + 1 < n && nums[i] === nums[i + 1]) {
continue;
}
ans.push(nums[i]);
if (--k === 0) {
break;
}
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Try every possible combination of choices. With n items each having two states (include/exclude), the search space is 2ⁿ. Evaluating each combination takes O(n), giving O(n × 2ⁿ). The recursion stack or subset storage uses O(n) space.
Greedy algorithms typically sort the input (O(n log n)) then make a single pass (O(n)). The sort dominates. If the input is already sorted or the greedy choice can be computed without sorting, time drops to O(n). Proving greedy correctness (exchange argument) is harder than the implementation.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: Locally optimal choices may fail globally.
Usually fails on: Counterexamples appear on crafted input orderings.
Fix: Verify with exchange argument or monotonic objective before committing.