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:

Input: nums = [3, 4, 2]
Output: 6
Explanation: 
Delete 4 to earn 4 points, consequently 3 is also deleted.
Then, delete 2 to earn 2 points. 6 total points are earned.

Example 2:

Input: nums = [2, 2, 3, 3, 3, 4]
Output: 9
Explanation: 
Delete 3 to earn 3 points, deleting both 2's and the 4.
Then, delete 3 again to earn 3 points, and 3 again to earn 3 points.
9 total points are earned.

Note:

  • The length of nums is at most 20000.
  • Each element nums[i] is an integer in the range [1, 10000].

 

经过同学提示,这道题竟然是LeetCode 198. House Robber —— 打家劫舍的变种题。遇到一个数,要么选,要么不选。如果选了就不能选和它相邻的数,想一想还真是打家劫舍。既然知道是打家劫舍,那么就按照打家劫舍的思路来做一下。本题的index不是相邻的条件,而是数字本身。那么想要类比打家劫舍那样做就需要先对数组进行排序,并且去重。因为如果一旦选择一个数,或者不选其相邻的数,和它数值一样的数都需要选或者不选。那么就出现一个问题,排序是否真的必要?本题之所以不用排序是因为下面的note给了数字的限制,即每个数字都在[1, 10000]范围内。而我们只需要知道每个元素的个数就可以完成本题对打家劫舍的类比:建立一个大小为10001的数组,以数字本身作为index,数字出现的次数作为新数组的值。这样就有了一个以原数组元素值为index的数组,其index对应值为index在原数组中出现次数。那么就等同于打家劫舍了,

 

稍微变化一下写法,就可以直接把数字出现次数融合到新数组里,变成一个以原数组元素为index,该原数组元素总分数为新数组元素值的新数组。之后直接利用这个包含总分数值得新数组进行动态规划即可。

 


解法一(Java)

class Solution {
    public int deleteAndEarn(int[] nums) {
        if (nums == null || nums.length == 0) return 0;
        int[] freq = new int[10001];
        for (int num : nums)
            freq[num]++;
        int dp1 = freq[0] * 0;
        int dp2 = Math.max(dp1, freq[1]*1);
        int dp = dp2;
        for (int i = 2; i < 10001; i++) {
            dp = Math.max(dp1 + freq[i] * i, dp2);
            dp1 = dp2;
            dp2 = dp;
        }
        return dp;
    }
}

 

解法二(Java)

class Solution {
    public int deleteAndEarn(int[] nums) {
        if (nums == null || nums.length == 0) return 0;
        int[] sum = new int[10001];
        for (int num : nums)
            sum[num] += num;
        for (int i = 2; i < 10001; i++)
            sum[i] = Math.max(sum[i-1], sum[i-2] + sum[i]);
        return sum[10000];
    }
}

 

posted on 2018-08-29 11:43  小T在学习  阅读(334)  评论(0编辑  收藏  举报