在数组中选择一个数并删除+-1的值,求得到数组的最大和 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].

解决:

【题意】

给定整数数组nums,执行如下操作:

挑选任意数字nums[i],得到nums[i]分,同时需要删除所有等于nums[i] - 1和nums[i] + 1的整数。

求最大得分。

①  动态规划。

House Robber类似,对于每一个数字,我们都有两个选择,拿或者不拿。如果我们拿了当前的数字,我们就不能拿之前的数字(如果我们从小往大遍历就不需要考虑后面的数字),那么当前的积分就是不拿前面的数字的积分加上当前数字之和。如果我们不拿当前的数字,那么对于前面的数字我们既可以拿也可以不拿,于是当前的积分就是拿前面的数字的积分和不拿前面数字的积分中的较大值。

take和skip分别表示拿与不拿上一个数字,takei和skipi分别表示拿与不拿当前数字。

class Solution { //18ms
    public int deleteAndEarn(int[] nums) {
        int[] sums = new int[10001];
        int take = 0;
        int skip = 0;
        for (int n : nums){
            sums[n] += n;
        }
        for (int i = 0;i < 10001;i ++){
            int takei = skip + sums[i];
            int skipi = Math.max(skip,take);
            take = takei;
            skip = skipi;
        }
        return Math.max(skip,take);
    }
}

② sums[i]表示到当前值为止的最大值。

class Solution { //11ms
    public int deleteAndEarn(int[] nums) {
        int[] sums = new int[10001];
        for (int n : nums){
            sums[n] += n;
        }
        for (int i = 2;i < 10001;i ++){
            sums[i] = Math.max(sums[i - 1],sums[i - 2] + sums[i]);
        }
        return sums[10000];
    }
}

转载于:https://my.oschina.net/liyurong/blog/1608874

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值