LeetCode740. Delete and Earn

探讨了如何从整数数组中通过删除元素获得最大得分的问题。采用动态规划与桶排序结合的方法,实现高效求解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

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


题目分析:

题目意思是从数组中取一个数获得这个数值的point并把这个数删掉,但是之后这个数-1或者+1的数的point都不能得到,如此重复直到没有数可以取,问怎么取可以获得最多的point。
首先我们可以知道所有数值相同的数一旦取了其中一个其他都可以取,也就是数值相同的数对待方法肯定是一样的,因此我们想到用桶来把数值相同的数都变成一个存放他们总和的桶,这样问题就变成了取桶的问题。
然后我们用动态规划的思路,用dp[i]表示0到i号桶能得到的最大point,当我们新增一个桶,我们有两种选择,一种是取一种不取,当我们取这个桶的时候,意味着我们不能取i-1号桶,这时候point变成bucket[i] + dp[i-2],由这个桶的值和还没有i-1号桶的dp[i-2]决定
当我们不取这个桶的时候,意味着情况和只有i-1个桶是一样的,这时候point和dp[i-1]是一样的
因此每新增一个桶,dp[i]为上面两种情况的最大值决定

c++代码:

class Solution {
public:
    int max(int a, int b) {
        if (b > a) return b;
        else return a;
    }
    int deleteAndEarn(vector<int>& nums) {
        int* bucket = new int[10001];
        int* dp = new int[10001];
        for (int i = 0; i < 10001; i++) {
            bucket[i] = 0;
        }
        for (int i = 0; i < nums.size(); i++) {
            bucket[nums[i]] += nums[i];
        }
        dp[0] = 0;
        dp[1] = bucket[1];
        for (int i = 2; i < 10001; i++) {
            dp[i] = max(dp[i-2]+bucket[i], dp[i-1]);
        }
        return dp[10000];
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值