您的位置:首页 > 其它

leetcode练习 Delete and Earn

2018-01-07 22:02 316 查看
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: 6
Explanation:
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: 9
Explanation:
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].

又是一道动态规划的题目,这次是凭着感觉写的,试了试,居然过了,原理想的并不是很明白,相信日后一定能研究透动态规划。

class Solution {
public:
int deleteAndEarn(vector<int>& nums) {
sort(nums.begin(), nums.end());
vector<int> values(10001, 0);
for(int i = 0; i < nums.size(); i++) {
values[nums[i]] += nums[i];
}
vector<int> dp(10001, 0);
dp[1] = values[1];
dp[2] = max(values[1], values[2]);
for (int i = 3; i < 10001; i++) {
dp[i] = max(dp[i-1], dp[i-2]+values[i]);
}
return dp[10000];
}
};


只有个大概的感觉:

我发现选中一个数时必然会把这个数出现的所有次数计算到后,就把每个数的代价统一计算,保存到数组values,如果原数组没有涉及到这个数,就记为0。

设了个专门用来动态规划的dp(其实是因为知道在动态规划的分类下的题目才故意这么做)

初始状态:dp[1]=values[1],只能取1了。dp[2]为values[1],values[2]的较大值。

状态转移:dp[i] = max(dp[i-1],dp[i-2]+values[i])

该决定这个数取还是不取的时候,如果不取这个数(选择dp[i-1],因为选择dp[i-1]的时候是必然不会取到values[i]的)那么就选dp[i-1],如果取这个数,当前值就会变成dp[i-2]+values[i],因为values[i-1]是一定不会取到的,至于i+1如何处理,我也说不清楚。基本是凭感觉在写。

其实换个思路,题目的意思也就是,给出你一串从1~10000的数的价值,让你在这些数里面选出价值最大的组合。条件是相邻的数不能同时选。这样看来的话,算法感觉稍微能理解了一丢丢。。。。。。为了利益最大化,不相邻的能选就要选,所以选dp[i-2]?感觉还是有点不对头,但总归有了那么点感觉,还是需要勤加练习才行。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: