题目连接:https://leetcode-cn.com/problems/delete-and-earn/
数组类型的子问题考虑dp[i]和dp[i-1],dp[i-2]的关系
代码:
#include<bits/stdc++.h>
#include <iostream>
using namespace std;
class Solution {
public:
int deleteAndEarn(vector<int>& nums) {
int len = nums.size();
if(len == 1){
return nums[0];
}
int max_num = 0;
for(int i=0; i<len; i++){
if(nums[i] > max_num){
max_num = nums[i];
}
}
max_num += 1;
int arr[max_num];
memset(arr, 0, sizeof(arr));
for(int i=0; i<len; i++){
arr[nums[i]] ++ ;
}
int dp[max_num];
memset(dp, 0, sizeof(dp));
int ans = 0;
dp[0] = 0;
dp[1] = arr[1]*1;
// dp[2] = max(dp[1], arr[2]*2);
ans = max(dp[1], dp[2]);
for(int i=2; i<max_num; i++){
dp[i] = max(dp[i-1], arr[i]*i+dp[i-2]);
ans = max(ans, dp[i]);
}
// for(int i=0; i<max_num; i++){
// cout<<arr[i]<<" ";
// }
// cout<<endl;
// for(int i=0; i<max_num; i++){
// cout<<dp[i]<<" ";
// }
// cout<<endl;
return ans;
}
};