您的位置:首页 > 其它

740. Delete and Earn

2017-12-18 16:47 465 查看
问题描述:

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.
给一个数组,每次选择一个数nums[i],可获得nums[i]的分数,同时要抛弃nums[i]-1和nums[i]+1的数,求最大得分
问题解决:

定义一个数组n,n[i]表示数值为i的数在数组中有多少个

定义一个数组point,point[i]表示从数值0到数值i遵循以上规则选择抛弃可获得的最大分数,有以下递推式

point[i] = Math.max(point[i-1], point[i-2] + i * n[i])

代码如下:

class Solution {

public:

    int deleteAndEarn(vector<int>& nums) {

        //若长度为0,返回0

        if(nums.size() == 0) return 0;

        //定义数组n并初始化

        vector<int> n(10001,0);

        int i;

        //循环算出每个数值的个数

        for(i = 0; i < nums.size(); i++) n[nums[i]]++;

        //定义数组point

        vector<int> points(10001,0);

        points[1] = n[1];

        //根据递推式算出数值0到i可获得的最大分数

        for(i = 2; i < 10001; i++) {

            points[i] = points[i-1] > points[i-2]+i*n[i] ? points[i-1] : points[i-2]+i*n[i];

        }

        return points[10000];

    }

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: