Delete and Earn
ID: 740
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] - 1
and every element equal tonums[i] + 1
.
Return the maximum number of points you can earn by applying the above operation some number of times.
Idea
Since all same number can be added together without being deleted, same numbers should be clustered and calculate the sum of same numbers
Get the max number among the list and create an array of length max+1 to store all possible sums of a given number, e.g: arr[2] means the sum of all 3 (start from index 0, so plus 1)
Use the dp array to traverse the sum storage array. If current number is previous number+2, meaning that previous sum can add to current sum: dp[i-2]+arr[i]; If current number is previous number+1, meaning that current sum is deleted when calculating the previous sum, so that can only be dp[i-1]. Get the max among these two possible combinations
dp[dp.length-1] is the result of the max value obtaine
Code
Last updated