LeetCode#740 Delete and Earn (week16)

week16

题目

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.
这里写图片描述
Note:

· The length of nums is at most 20000.
· Each element nums[i] is an integer in the range [1, 10000].
原题地址:https://leetcode.com/problems/delete-and-earn/description/

解析

题目给定一些数(范围在1到10000),如果删除某个数n,则可以earn到这个数但值为n-1和n+1的数会被删除,求能够earn到的最大的值。
思路:可以用一般的动态规划思想来解决这个问题,从值1开始,计算到目前为止能earn到的最大值,对于某个值n,对应的最大值可由公式f(n)=max{f(n-1),f(n-2)+n*numsOf(n)}得到,前者表示取n-1(则n会被删除),后者表示取n(则n-1会被删除),从1开始循环执行最终到10000得到最后结果。

代码

class Solution {
public:
    int deleteAndEarn(vector<int>& nums) {
        vector<int> count(10001, 0);
        for (int i = 0; i < nums.size(); ++i) {
            ++count[nums[i]];
        }
        int *earn = new int[10001];
        earn[1] = count[1];
        for (int i = 2; i < 10001; ++i) {
            earn[i] = max(earn[i - 1], earn[i - 2] + count[i] * i);
        }
        return earn[10000];
    }
    int max(int a, int b) {
        return a > b ? a : b;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值