题目地址
题目描述
Given an array nums
of integers, you can perform operations on the array.
In each operation, you pick any nums[i]
and delete it to earn nums[i]
points. After, you must delete every element equal to nums[i] - 1
or nums[i] + 1
.
You start with 0 points. Return the maximum number of points you can earn by applying such operations.
Example 1:
1 | Input: nums = [3, 4, 2] |
Example 2:
1 | Input: nums = [2, 2, 3, 3, 3, 4] |
Note:
The length of nums
is at most 20000
.
Each element nums[i]
is an integer in the range [1, 10000]
.
解题思路
很经典的DP题。与此类似的有Best Time to Buy and Sell Stock with Transaction Fee。
由于delete一个数字的话,和它相差1的数字将不给得分(即如果删除3,则只能得到3的分,2与4的不能得到),所以我们使用两个变量来维护()take 与 skip),一个用来保存删除当前数字后的分数(take),一个用来保存不删除当前数字(skip)(即删除与它相差1的数字)。
由于题目要求delete一个数字的话必须删除与相差1的数字,所以我们的take的计算式为:
take = skip + nums.value * nums.count
而skip则是取skip与更新前的take中的较大值(skip保存的是不删除当前的值的最大分数,即上一步中的take与skip较大值)。
skip = max(take , skip)
解题代码【.CPP】
1 | class Solution { |