LeetCode动态规划 删除并获得点数

You are given an integer array nums. You want to maximize the number of points you get by performing the following operation any number of times:

Pick any nums[i] and delete it to earn nums[i] points. Afterwards, you must delete every element equal to nums[i] - 1 and every element equal to nums[i] + 1.
Return the maximum number of points you can earn by applying the above operation some number of times.

这道题是我做动态规划碰到的第一个下马威,没有识别出这是一道动态规划题。实际上,这题跟“打家劫舍”那道题的核心思想是一模一样的。重点是如何理解获得一个数后,就要删除和它相邻的数。其实,可以将这句话转述成:不能取两个相邻的数。这样就很容易地解决了本题。

状态转移方程
dp[i] = max(dp[i-2] + dp[i], dp[i-1])
边界条件
dp[0] = dp[0], dp[1] = max(dp[0], dp[1])

class Solution {
public:
    int deleteAndEarn(vector<int>& nums) {
        int nums_top = nums.size();
        if(nums_top == 0)
        return 0;
        else if(nums_top == 1)
        return nums[0];

        int dp[20005] = {0};
        int maxn = -1;
        for(int i = 0; i < nums_top; i++)
        {
            dp[nums[i]] += nums[i];
            if(nums[i] > maxn)
            maxn = nums[i];
        }
        dp[1] = max(dp[0], dp[1]);
        for(int i = 2; i <= maxn; i++)
        dp[i] = max(dp[i-2]+dp[i], dp[i-1]);
        
        return dp[maxn];
    }
};
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值