其实跟打家劫舍没啥区别 排序去重之后去考虑当前位置和前两个位置之间的关系即可,具体见代码:
class Solution {
public:
int deleteAndEarn(vector<int>& nums) {
int n = nums.size();
if (n == 1) return nums[0];
unordered_map<int, int> hash;
for (int i = 0; i < n; i++) {
++hash[nums[i]];
}
sort(nums.begin(), nums.end());
int n1 = (unique(nums.begin(), nums.end()) - nums.begin());
vector<int> dp(n1 + 1, 0);
dp[0] = 0; dp[1] = nums[0] * hash[nums[0]];
for (int i = 1; i < n1; i++) {
if (nums[i] - nums[i - 1] == 1) {
dp[i + 1] = max(dp[i - 1] + nums[i] * hash[nums[i]], dp[i]);
}
else {
dp[i + 1] = dp[i] + nums[i] * hash[nums[i]];
}
}
return dp[n1];
}
};