https://leetcode.com/problems/delete-and-earn/description/
跟买卖股票的还是一样的思路。
参考率 https://leetcode.com/problems/delete-and-earn/discuss/123634/C++-9ms-DP-solution
class Solution {
public:
int deleteAndEarn(vector<int>& nums) {
int n = nums.size();
if (n == 0) return 0;
vector< vector<int> > dp( nums.size() + 1, vector<int>(2) );
sort(nums.begin(), nums.end());
// 0表示不要这个数,1表示要这个数
dp[0][0] = 0;
dp[0][1] = nums[0];
for (int i = 1; i < nums.size(); i++) {
if (nums[i] == nums[i-1]) {
dp[i][0] = dp[i-1][0];
dp[i][1] = dp[i-1][1] + nums[i];
continue;
}
dp[i][0] = max(dp[i-1][0], dp[i-1][1]);
dp[i][1] = nums[i] == nums[i-1] + 1 ? dp[i-1][0] + nums[i] : dp[i][0] + nums[i];
}
return max(dp[n-1][0], dp[n-1][1]);
}
};
https://leetcode.com/problems/delete-and-earn/discuss/109871/Awesome-Python-4-liner-with-explanation-Reduce-to-House-Robbers-Question
这里有个非常好的 hash转化成house robber的做法。当时我想到这个题感觉跟不能取相邻的XXX的感觉一样,但是没想到咋做。。
class Solution {
public:
int deleteAndEarn(vector<int>& nums) {
vector<int> dp(10000+1, 0);
for (int i = 0; i < nums.size(); i++) {
dp[ nums[i] ] += nums[i];
}
int last = 0, cur = 0;
for (int i = 0; i < dp.size(); i++) {
// cur其实是选了i-1的,last是cur之前的选择
int tmp = cur;
cur = max(last + dp[i], cur);
last = tmp;
}
return cur;
}
};