Delete and Earn问题及解法
来源:互联网 发布:淘宝网千人千面 编辑:程序博客网 时间:2024/06/06 00:23
问题描述:
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.
示例:
Input: nums = [3, 4, 2]Output: 6Explanation: Delete 4 to earn 4 points, consequently 3 is also deleted.Then, delete 2 to earn 2 points. 6 total points are earned.
Input: nums = [2, 2, 3, 3, 3, 4]Output: 9Explanation: 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.
问题分析:
本题转换一下就跟House Robber差不多了,有点贪心的意思。统计每个数字的出现的和,例如,nums = [2,2,3,3,3,4]中,2的和是4,3的和是9,4的和是4.
然后组成新的数组[2,3,4],这些数字就代表着是否相邻,2,3相邻,3,4相邻,这时再利用house robber的解法即可求解。
过程详见代码:
class Solution {public: int deleteAndEarn(vector<int>& nums) { vector<int> res(10001, 0);for (auto n : nums){res[n] += n;}vector<int> dp(10001, 0);dp[1] = res[1];for (int i = 2; i <= 10000; i++){dp[i] = max(dp[i - 1], dp[i - 2] + res[i]);}return dp[10000]; }};
阅读全文
0 0
- 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
- Leetcode | Delete and Earn
- 740. Delete and Earn
- Delete and Earn
- 740. Delete and Earn
- 740. Delete and Earn
- 740[Medium]:Delete and Earn
- Leetcode:740. Delete and Earn
- LeetCode | 740. Delete and Earn
- [leetcode] 740. Delete and Earn
- 大顶堆排序
- Windows x64免按F8加载驱动文件
- Android dialog不同的显示方式
- 设计模式(二十二)——享元模式
- List集合转Json
- Delete and Earn问题及解法
- Spring整合Redis(spring-data-redis)
- C#启动打印机打印文件
- Android Unity 交互
- 输入两个整数m和n,及另一个整数k,计算m/n,结果精确到小数点后k位。
- iOS 静态库的打包及使用(swift_oc)
- Android Studio Git实现回退至某一个版本
- 最小费用最大流/费用流zkw算法模板(洛谷3381)
- android ANR分析