在數組中選擇一個數並刪除+-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];     } }

相關文章
相關標籤/搜索