Maximize Points by Deleting Values and Their Neighbors
MicrosoftSoftware Engineer · Online AssessmentLast updated
Tests dynamic programming and hash map aggregation to maximize points under adjacency constraints over a sparse range of values.
Problem Statement
You are given an integer array nums. In one operation, you can pick any element with value x, add x to your total score, and remove it from the array. However, doing so immediately deletes all occurrences of x - 1 and x + 1 from the array without earning any points for them.
You can repeat this operation until the array is empty.
Return the maximum number of points you can achieve. Note that values in nums can be very large and sparse, so your solution must be efficient with respect to both time and space.
Interface
def max_points(nums: list[int]) -> int:
pass
Input & Output Format
- Input:
nums, a list of non-negative integers. - Output: An integer representing the maximum possible score.
Constraints
1 <= len(nums) <= 10^51 <= nums[i] <= 10^9
Examples
Example 1
Input: nums = [3, 4, 2]
Output: 6
Explanation:
- Pick 4: score = 4. Deletes 3.
- Remaining elements: [2].
- Pick 2: score = 4 + 2 = 6.
Total score = 6.
Example 2
Input: nums = [2, 2, 3, 3, 3, 4]
Output: 9
Explanation:
- Pick all 3s (total 3 * 3 = 9 points). This deletes all 2s and 4s.
Alternatively, picking all 2s (4 pts) and all 4s (4 pts) gives 8 points.
The maximum possible score is 9.
Edge Cases
- A single element array (e.g.,
[5]returns5). - Arrays where elements are far apart (e.g.,
[1, 1000000000]), where picking one does not affect the other. - Arrays with many duplicates of the same number.
Hints
Hint 1
Notice that if you decide to take any instance of value x, you should take all instances of x because the first choice already deletes all occurrences of x - 1 and x + 1.
Hint 2
Aggregate the total points available for each unique value (value * count) using a hash map.
Hint 3
Sort the unique values and apply dynamic programming similar to the House Robber problem, checking whether the current value is strictly equal to the previous value plus 1.
Follow-up questions
- How would you adapt your solution if choosing x deleted all values in the range [x - k, x + k] for a given integer k >= 1?
- Could you solve this with O(1) auxiliary space if you are allowed to modify the input array in-place?
- How would you handle this problem in an online streaming setting where numbers arrive one at a time and you need to query the maximum score at any point?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.