LeetCode#740 Delete and Earn (week16)
来源:互联网 发布:张大奕的淘宝店质量 编辑:程序博客网 时间:2024/06/07 14:46
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; }};
- LeetCode#740 Delete and Earn (week16)
- Leetcode | Delete and Earn
- Leetcode:740. Delete and Earn
- LeetCode | 740. Delete and Earn
- [leetcode] 740. Delete and Earn
- [LeetCode]740. Delete and Earn
- Leetcode 740. Delete and Earn
- 740[Medium]:Delete and Earn
- 740. Delete and Earn
- Delete and Earn
- 740. Delete and Earn
- 740. Delete and Earn
- 740. Delete and Earn
- 740. Delete and Earn
- 740. Delete and Earn
- 740. Delete and Earn
- 740. Delete and Earn
- Delete and Earn
- Nginx简单的代理配置
- 九九乘法表
- 从12星座支付宝交易记录窥探小秘密
- 面向比特的链路控制规程HDLC和点对点协议
- VMware发布新版vSphere6.5虚拟化平台,助力企业数字化转型
- LeetCode#740 Delete and Earn (week16)
- 数据中心管理人员预计2018年发生的变化
- LINUX下的一些小工具
- 在Linux中配置ssh密钥,在Git中使用SSH协议访问Github
- 2017最具内容价值APP榜单发布:人人都是产品经理获「年度产品技术类MVP应用」
- 新技术,新挑战,新能力:金融+AI 的产品实践
- 解决Xshell关闭vim后内容仍停留在屏幕的问题
- 写了10篇产品分析后,我似乎知道怎么做一款短视频产品了……
- 你说我是佛系运营,而我身上却有你的影子