KatInterview

Select Numbers to Maximize Score with Neighbor Elimination

Dynamic ProgrammingAuto-graded · 22 test cases
MediumAuto-gradedDynamic Programminghash-mapsortinghouse-robber-variant

Last 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 x that still exists in the array
  • Gain x points
  • Remove one occurrence of x from the array
  • Immediately remove all occurrences of both x - 1 and x + 1 from 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^5
  • 1 <= 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.