[动态规划] leetcode 740 Delete and Earn
problem:https://leetcode.com/problems/delete-and-earn/
爬台阶类型dp。首先需要进行排序,并记录每个数出现的数字,为了方便这里使用了ordered_map。因为情况是对称的,可以只考虑前一位数字是否比当前位数字恰好小1, 如果是,就需要从dp[ i - 2] 转移过来,否则,直接从dp[ i ] 转移过来。
class Solution { public: map<int, int> m; int deleteAndEarn(vector<int>& nums) { if (nums.size() == 0) return 0; for (int i = 0; i < nums.size(); i++) { m[nums[i]]++; } auto it = m.begin(); auto last_it = it; vector<int> dp(m.size(), 0); dp[0] = it->first * it->second; it++; int i = 1; for (; it != m.end(); it++,i++) { if (it->first == last_it->first + 1) { if (i >= 2) dp[i] = max(dp[i - 2] + it->first * it->second, dp[i - 1]); else dp[i] = max(it->first * it->second, dp[i - 1]); } else { dp[i] = dp[i - 1] + it->first * it->second; } last_it = it; } return dp[m.size() - 1]; } };