class Solution {
public:
int deleteAndEarn(vector<int>& nums) {
if (nums.size() == 0) return 0;
std::sort(nums.begin(), nums.end());
int count = 1;
int now = nums[0];
vector<pair<int,int>> v;
for (int i = 1; i < nums.size(); i++) {
if (now != nums[i]) {
v.push_back(make_pair(now, count));
now = nums[i];
count = 1;
} else {
count++;
}
}
v.push_back(make_pair(now, count));
vector<int> answer(v.size(), 0);
answer[0] = (v[0].first * v[0].second);
int score_with;
for (int i = 1; i < v.size(); i++) {
if (v[i].first == (v[i - 1].first + 1)) {
score_with = (v[i].first * v[i].second) + ((i > 1) ? (answer[i - 2]) : (0));
} else {
score_with = (v[i].first * v[i].second) + (answer[i - 1]);
}
answer[i] = ((score_with > answer[i - 1]) ? score_with : answer[i - 1]);
}
return answer[v.size() - 1];
}
};
留言
張貼留言