leetcode习题整理——动态规划篇——lc740. Delete and Earn

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].

感觉是比较奇怪的一道题,最开始没看到note的提示,是先对数组进行sort然后二维dp做的,不过TLE了,参考了下后面的solution,整理思路如下。

本题的关键在于note中提示的所有数字介于1到10000之间,既然给定了数字的范围,那我们很快就能联想到利用bucket sort的思路,将数组中所有的数放入到10000个bucket中,便实现了对原数组的排序。然后,对每个bucket中存的数,我们都可以采取两种策略,既取或者不取,因此我们可以对bucket从小到大遍历,对期中每个数采取这两种策略,并记录最大的取值,再遍历至下一个值。思路类似爬梯子,小偷还有买卖股票等一系列的题。

    public int deleteAndEarn(int[] nums) {
        int[]buckets = new int[10001];
        for (Integer i:nums) {
            buckets[i]++;
        }
        int prevNum = -1;
        int includePrev = 0;
        int excludePrev = 0;
        for(int i = 0; i < buckets.length; i++){
            if(buckets[i] != 0){
                int max = Math.max(includePrev,excludePrev);
                if(i != prevNum+1){
                    includePrev = i * buckets[i] + max;
                    excludePrev = max;
                } else {
                    includePrev = i * buckets[i] + excludePrev;
                    excludePrev = max;
                }
                prevNum = i;
            }
        }
        return Math.max(includePrev,excludePrev);
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值