Problem Description
Given an integer array nums, you want to maximize the number of points by repeatedly performing the following operation: choose any number nums[i], earn points equal to nums[i], and then delete all elements equal to nums[i] - 1 and nums[i] + 1. Return the maximum points you can achieve.
Key Insights
- Transform the problem by aggregating points for each unique number, similar to grouping.
- Realize that if you earn points from number x, you cannot earn points from x-1 and x+1.
- The problem resembles the House Robber problem where adjacent houses (numbers) cannot be robbed (taken).
- Use dynamic programming to decide whether to take or skip each unique number.
Space and Time Complexity
Time Complexity: O(max + n) where max is the maximum number in nums (since we iterate through a frequency array up to max) and n is the length of nums. Space Complexity: O(max) for the frequency and dp arrays.
Solution
The solution begins by using a hash table (or frequency array) to compute the total points that can be earned from each unique number (i.e., points = number * frequency). Then, we convert the problem to one similar to the House Robber problem: for each number i, decide to either take dp[i-2] plus the current total points at i or skip i and take dp[i-1]. This decision is captured in the recurrence relation dp[i] = max(dp[i-1], dp[i-2] + total[i]). Finally, return dp[max_num] as the result.