You have an array of whole numbers nums and play a game to collect points. In one move you pick any number x still in the array, remove it, and earn x points. As a cost, every copy of x − 1 and every copy of x + 1 is removed too, and those earn nothing.
You may make as many moves as you like. Return the largest total you can earn.
Example 1
Input: nums = [3,4,2,3,5] Output: 11 Why: take both 3s and the 5 (3 + 3 + 5); that wipes out the 2 and the 4
2 more examples and the constraints
Example 2
Input: nums = [1,1,1,2,6] Output: 9 Why: the three 1s (3) beat the single 2, and 6 has no neighbours
Example 3
Input: nums = [10,20,10] Output: 40 Why: no two values are next to each other, so take them all
Constraints
- 1 ≤ nums.length ≤ 20,000
- 1 ≤ nums[i] ≤ 10,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Count, sort, DP over distinct valuesO(n log n)
- Value buckets + House RobberO(n + M)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 20,000 numbers | Verdict |
|---|---|---|---|
| Count, sort, DP | O(n log n) | Passes; handles sparse values | |
| Value buckets + House Robber | O(n + M) | Best; no sort, two numbers |
n = length of nums, M = largest value (at most 10,000).
Edge cases to test
- One number. [7] earns 7.
- All the same value. [5,5,5,5] earns 20: the first pick deletes no other 5.
- A full run of values. 1 to 10 each once: take the even ones for 30, not the odd ones for 25.
- Gaps between values. [1,3,5] has no conflicts, so all 9 points count.
- Many copies win. [2,2,2,3] takes the three 2s for 6 rather than the single 3.
Common mistakes
- Thinking only one copy of x is earned per move, and missing that all copies should be taken.
- Using
best[i − 1]without checking that the previous value is really v − 1, which wrongly blocks values after a gap. - Greedily taking the largest value first; [1,1,1,2] shows the single 2 is the worse pick.
How to talk through it
- 1Clarify. Do copies of x itself get deleted when I take x? Can values repeat? What is the range of values?
- 2Simplify the game. Taking x once means taking every copy, so each value is worth value × count.
- 3Name the pattern. Values in a row where neighbours conflict: this is House Robber.
- 4Code the buckets. points[v] per value, then prev and cur through the slots.
- 5Test out loud. Run a single number, all copies of one value and a run like 1 to 10.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?