week17-leetcode #740-DeleteandEarn

week17-leetcode #740-DeleteandEarn

链接:https://leetcode.com/problems/delete-and-earn/description/

Question

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

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.

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

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

Solution

class Solution {
public:
  #define MAX_SIZE 10000
  int deleteAndEarn(vector<int>& nums) {
    int size = nums.size();
    int* cnt = new int[MAX_SIZE];
    int* dp = new int[MAX_SIZE];
    vector<int> new_nums(MAX_SIZE, 0);
    for (int i = 0; i < MAX_SIZE; i++) {
      cnt[i] = dp[i] = 0;
    }

    // 统计数目
    for (int i = 0; i < size; i++)
      cnt[nums[i]]++;

    for (int i = 0; i < MAX_SIZE; i++) {
      if (cnt[i] != 0) {
        new_nums[i] = i*cnt[i];
      } else {
        new_nums[i] = 0;
      }
    }
    dp[0] = 0;
    dp[1] = new_nums[1];
    for (int i = 2; i < MAX_SIZE; i++) {
      dp[i] = max(dp[i-1], dp[i-2]+new_nums[i]);
    }
    delete []cnt;
    delete []dp;
    return dp[MAX_SIZE-1];
  }
};

思路:这个题意是:随机删除一个数字A,可以加上A的得分,并要求删除所有等于A-1或者A+1的其他数字,其实这道题稍微转一下就和House Rob类似了。实际上,可以将同样的数字归成一个整体,所以我才用了一个cnt数组记录更数字出现的次数。然后新创建一个新的数组new_nums,用来模拟House Rob中的数组,实际上,注意到new_nums元素是从小排到大的,但是未必连续,所以不完全是House Rob的情景。只要人为让没出现的数字对应的值是0,就可以模拟出相邻的情况了。得到new_nums之后,后面的解法就和House Rob差不多。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值