Problem
You are given an integer array nums. You want to maximize the number of points you get by performing the following operation any number of times:
- Pick any
nums[i]and delete it to earnnums[i]points. Afterwards, you must delete every element equal tonums[i] - 1and every element equal tonums[i] + 1.
Return the maximum number of points you can earn by applying the above operation some number of times.
Examples
Example 1:
| |
Example 2:
| |
Solution
Method 1 - DP
To solve this problem, we can use a dynamic programming approach similar to the “house robber” problem. Here’s the step-by-step approach:
- Count Frequency of Each Element: First, count the total points you would get if you deleted each element independently. This can be done using a frequency array or a dictionary.
- Use Dynamic Programming: Create a dp array where
dp[i]represents the maximum points that can be earned considering all elements from0toi. The dynamic programming transitions are:- If you do not choose
i, the points are the same as not choosingi-1, i.e.,dp[i-1]. - If you choose
i, you add the points fromito the points obtained fromi-2, because choosingirequires removing elementsi-1.
- If you do not choose
Code
| |
| |
Complexity
- ⏰ Time complexity:
O(n + m)wherenis the length of the input arraynumsandmis the range of the numbers innums. Building the frequency array/dictionary and the dp array takes linear time relative to the range and the number of elements. - 🧺 Space complexity:
O(m)for the dp array and the frequency count if using a dictionary.