Select Numbers to Maximize Score with Neighbor Elimination
Dynamic ProgrammingAuto-graded · 22 test casesLast updated
Tests dynamic programming on sparse integers and hash map frequency counting to find the optimal subset when adjacent values conflict.
You are given an array of integers nums. You can perform the following operation repeatedly:
- Choose any value
xthat still exists in the array - Gain
xpoints - Remove one occurrence of
xfrom the array - Immediately remove all occurrences of both
x - 1andx + 1from the array (you earn nothing for these removed elements)
Continue performing operations until you cannot gain any more points.
Return the maximum total points you can accumulate.
Note: The integers in nums may be very large and sparse, so your solution must handle this efficiently.
Constraints
1 <= nums.length <= 10^51 <= nums[i] <= 10^9
Examples
Example 1
Input: select_numbers([3, 4, 2])
Output: 6
Example 2
Input: select_numbers([2, 2, 3, 3, 3, 4])
Output: 9
Hints
Hint 1
If you choose a value once, choosing it again doesn't cause any additional deletions—think about what this means for your strategy.
Hint 2
This problem is similar to the classic House Robber problem, but on the distinct values present in the array rather than on array indices.
Hint 3
Use a hash map to aggregate the total points available for each distinct value, then apply dynamic programming on the sorted unique values.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The key insight is to recognize two critical properties:
1. If you select a value once, select all occurrences of that value. The first time you choose value x, all instances of x-1 and x+1 are deleted. Subsequent selections of x don't trigger additional deletions, so they provide free points. Therefore, each unique value is an all-or-nothing decision worth value × count points.
2. The only conflicts are between consecutive integers. Selecting value v only prevents you from selecting v-1 and v+1. This transforms the problem into selecting a maximum-weight subset of distinct values where no two chosen values are consecutive integers.
This is equivalent to the House Robber problem, but applied to the sorted list of distinct values that appear in the input, rather than array positions.
Algorithm
- Use a hash map to compute the total points available for each distinct value (value × frequency)
- Sort the distinct values
- Apply dynamic programming with two states:
dp_prev_prev: best score up to two values agodp_prev: best score up to the previous value
- For each value in sorted order:
- If it's consecutive with the previous value (
value == prev_value + 1), we have a conflict: take the maximum of skipping the current value or taking it (which means skipping the previous) - If there's a gap, no conflict exists, so always take the current value
- If it's consecutive with the previous value (
- Return the final best score
The hash map approach is essential because values can reach 10^9, making array-based indexing infeasible.
Correctness
Any valid selection corresponds to a set of distinct values with no two consecutive integers. The total score is the sum of (value × count) for each selected value. The DP recurrence explores all such valid selections and computes the maximum.
Complexity
- Time: O(n + u log u), where u is the number of distinct values (u ≤ n). In the worst case, this is O(n log n) for the sorting step. Aggregating values takes O(n), and the DP scan takes O(u).
- Space: O(u) for the hash map storing value frequencies. The DP uses only O(1) additional variables.
from collections import Counter
from typing import List
def select_numbers(nums: List[int]) -> int:
# Calculate total points available for each unique value
value_points = Counter()
for num in nums:
value_points[num] += num
prev_value = None
dp_prev_prev = 0 # best score excluding the last value
dp_prev = 0 # best score including up to the last value
for value in sorted(value_points):
if prev_value is not None and value == prev_value + 1:
# Current value conflicts with previous (they are consecutive)
# Either skip current or take current and skip previous
dp_current = max(dp_prev, dp_prev_prev + value_points[value])
else:
# No conflict: always beneficial to take current value
dp_current = dp_prev + value_points[value]
dp_prev_prev, dp_prev = dp_prev, dp_current
prev_value = value
return dp_prev