1. 程式人生 > >[leetcode]740. Delete and Earn

[leetcode]740. Delete and Earn

[leetcode]740. Delete and Earn


Analysis

唉 感覺應該GG了,還是好好刷題看論文吧—— [每天刷題並不難0.0]

Given an array nums of integers, you can perform operations on the array.
In each operation, you pick any nums[i] and delete it to earn nums[i] points. After, you must delete every element equal to nums[i] - 1 or nums[i] + 1.
You start with 0 points. Return the maximum number of points you can earn by applying such operations.
在這裡插入圖片描述


把相同的數放到以這個數為下標的bucket裡面,再定義兩個陣列take[]和skip[],然後用動態規劃解決,方程為:
take[i]=skip[i-1]+n[i]
skip[i]=max(take[i-1], skip[i-1])

Implement

class Solution {
public:
    int deleteAndEarn(vector<int>& nums) {
        vector<int> n(10001, 0);
        for(int num:nums)
            n[num] += num;
        vector<
int> take(10001, 0); vector<int> skip(10001, 0); for(int i=1; i<10001; i++){ take[i] = skip[i-1]+n[i]; skip[i] = max(skip[i-1], take[i-1]); } return max(take[10000], skip[10000]); } };