在数组中选择一个数并删除+-1的值,求获得数组的最大和 Delete and Earn

问题:数组

Given an array nums of integers, you can perform operations on the array.app

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.spa

You start with 0 points. Return the maximum number of points you can earn by applying such operations..net

Example 1:code

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:orm

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:blog

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

解决:ip

【题意】element

给定整数数组nums,执行以下操做:get

挑选任意数字nums[i],获得nums[i]分,同时须要删除全部等于nums[i] - 1和nums[i] + 1的整数。

求最大得分。

①  动态规划。

House Robber相似,对于每个数字,咱们都有两个选择,拿或者不拿。若是咱们拿了当前的数字,咱们就不能拿以前的数字(若是咱们从小往大遍历就不须要考虑后面的数字),那么当前的积分就是不拿前面的数字的积分加上当前数字之和。若是咱们不拿当前的数字,那么对于前面的数字咱们既能够拿也能够不拿,因而当前的积分就是拿前面的数字的积分和不拿前面数字的积分中的较大值。

take和skip分别表示拿与不拿上一个数字,takei和skipi分别表示拿与不拿当前数字。

class Solution { //18ms
    public int deleteAndEarn(int[] nums) {
        int[] sums = new int[10001];
        int take = 0;
        int skip = 0;
        for (int n : nums){
            sums[n] += n;
        }
        for (int i = 0;i < 10001;i ++){
            int takei = skip + sums[i];
            int skipi = Math.max(skip,take);
            take = takei;
            skip = skipi;
        }
        return Math.max(skip,take);
    }
}

② sums[i]表示到当前值为止的最大值。

class Solution { //11ms     public int deleteAndEarn(int[] nums) {         int[] sums = new int[10001];         for (int n : nums){             sums[n] += n;         }         for (int i = 2;i < 10001;i ++){             sums[i] = Math.max(sums[i - 1],sums[i - 2] + sums[i]);         }         return sums[10000];     } }

相关文章
相关标签/搜索