LeetCode-740. Delete and Earn

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.

Example 1:

Input: nums = [3, 4, 2]
Output: 6
Explanation: 
Delete 4 to earn 4 points, consequently 3 is also deleted.
Then, delete 2 to earn 2 points. 6 total points are earned.

Example 2:

Input: nums = [2, 2, 3, 3, 3, 4]
Output: 9
Explanation: 
Delete 3 to earn 3 points, deleting both 2's and the 4.
Then, delete 3 again to earn 3 points, and 3 again to earn 3 points.
9 total points are earned.

Note:

  • The length of nums is at most 20000.
  • Each element nums[i] is an integer in the range [1, 10000].

题解:构造hash表排除重复,并使用price存储每个不重复元素的代价,再使用不重复的新num进行dp。

转移方程:

num[i] != num[i - 1] + 1:dp[i] = max(dp[i - 1] + price[num[i]], dp[i - 1]);

扫描二维码关注公众号,回复: 4299095 查看本文章

num[i] == num[i - 1] :dp[i] = max(dp[i - 2] + price[num[i]], dp[i - 1]);

class Solution {
public:
  int deleteAndEarn(vector<int>& nums) {
    int n = nums.size();
    if (n == 0) {
      return 0;
    }
    sort(nums.begin(), nums.end());
    vector<int> price(nums[n - 1] + 1, 0);
    vector<int> num;
    for (int i = 0; i < n; i++) {
      price[nums[i]] += nums[i];
    }
    for (int i = 0; i <= nums[n - 1]; i++) {
      if (price[i] != 0) {
        num.push_back(i);
      }
    }
    int l = num.size();
    if (l == 1) {
      return price[num[0]];
    }
    vector<int> dp(l, 0);
    dp[0] = price[num[0]];
    if (num[1] == num[0] + 1) {
      dp[1] = max(dp[0], price[num[1]]);
    }
    else {
      dp[1] = dp[0] + price[num[1]];
    }
    for (int i = 2; i < l; i++) {
      if (num[i] == num[i - 1] + 1) {
        dp[i] = max(dp[i - 2] + price[num[i]], dp[i - 1]);
      }
      else {
        dp[i] = max(dp[i - 1] + price[num[i]], dp[i - 1]);
      }
    }
    return dp[l - 1];
  }
};

猜你喜欢

转载自blog.csdn.net/reigns_/article/details/84641359