LeetCode-740. Delete and Earn

网友投稿 962 2022-10-02

LeetCode-740. Delete and Earn

LeetCode-740. Delete and Earn

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: 6Explanation: 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: 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.

Note:

The length of​​nums​​​ is at most​​20000​​.Each element​​nums[i]​​​ is an integer in the range​​[1, 10000]​​.

题解:构造hash表排除重复,并使用price存储每个不重复元素的代价,再使用不重复的新num进行dp。

转移方程:

num[i] != num[i - 1] + 1:dp[i] = max(dp[i - 1] + price[num[i]], dp[i - 1]);

num[i] == num[i - 1] + 1:dp[i] = max(dp[i - 2] + price[num[i]], dp[i - 1]);

class Solution {public: int deleteAndEarn(vector& nums) { int n = nums.size(); if (n == 0) { return 0; } sort(nums.begin(), nums.end()); vector price(nums[n - 1] + 1, 0); vector num; for (int i = 0; i < n; i++) { price[nums[i]] += nums[i]; } for (int i = 0; i <= nums[n - 1]; i++) { if (price[i] != 0) { num.push_back(i); } } int l = num.size(); if (l == 1) { return price[num[0]]; } vector dp(l, 0); dp[0] = price[num[0]]; if (num[1] == num[0] + 1) { dp[1] = max(dp[0], price[num[1]]); } else { dp[1] = dp[0] + price[num[1]]; } for (int i = 2; i < l; i++) { if (num[i] == num[i - 1] + 1) { dp[i] = max(dp[i - 2] + price[num[i]], dp[i - 1]); } else { dp[i] = max(dp[i - 1] + price[num[i]], dp[i - 1]); } } return dp[l - 1]; }};

另一种思路:数据大小在10000之间,我们开一个10001的数组,保存每个数子给出的贡献,再从头遍历该数组寻找互不相邻的数字之间最大值:

class Solution {public: int deleteAndEarn(vector& nums) { int n = nums.size(), res = 0; vector vals(10001, 0); for (int i = 0; i < n; i++) { vals[nums[i]] += nums[i]; } int pre1 = vals[1], pre2 = 0; for (int i = 2; i < 10001; i++) { res = max(pre2 + vals[i], pre1); pre2 = pre1; pre1 = res; } return res; }};

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:LeetCode-876. Middle of the Linked List
下一篇:小程序必须和公众号名字一样吗(公众号名字和小程序名字可以相同吗)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~