Delete and Earn

  1. Delete and Earn

    • 题目
    • 代码块
    • 想法

Description

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.

代码

#include <iostream>
#include <vector>
using namespace std;

class Solution {
public:
    int deleteAndEarn(vector<int>& nums) {
        int delete1 = 0,notdelete1 = 0;
        int A[10001] = {0};
        int prenum = -1;
        for(int i = 0; i < nums.size(); i++){
            A[nums[i]] += 1; 
        }
        for(int i = 0; i <= 10000; i++){
            int m = max(delete1,notdelete1);
            if(A[i] != 0){
                if(i != prenum + 1) {
                    delete1 = i*A[i] + m;
                    notdelete1 = m;
                }
                else{
                    delete1 = notdelete1 + i*A[i];  
                    notdelete1 = m ;
                }
                prenum = i;
            }
        }
        return max(delete1,notdelete1);
    }
};
int main(){
    int A[] = {3,4,2};
    vector<int> arr1(A,A+3);
    Solution S;
    cout<<S.deleteAndEarn(arr1);
} 

想法

对于一个数,有两种操作,删除和不删除,对于该数来说,删除意味着前面的数一定是没有被删除,所以delete = 之前的notdelete + i*A[i];而不删除和前面没什么关系,前面无论删不删除都不影响现在这个数的不删除,所以如果这个数不删除,值为max(以前的notdelete,以前的delete),从0到10000,循环,最后比较notdelete和delete的值.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值