【leetcode】740. Delete and Earn

题目如下:

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.

Note:

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

解题思路:动态规划。首先我们把可以获得积分的删除为主动删除,不能获得积分的删除为被动删除。记dp[i][0] = v 表示被动删除值为i时,在nums中所有元素值为1~i时可以获得最大积分v,而dp[i][1] = v为主动删除i时获得的最大积分,那么有,

1. 被动删除i:那么i-1只能是主动删除,有dp[i][0] = dp[i-1][1]

2.主动删除i:i-1只能是被动删除,有dp[i][1] = dp[i-1][0] + 删除i可获得的积分

代码如下:

class Solution(object):
    def deleteAndEarn(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(nums) == 0: return 0
        dic = {}
        max_val = 0
        for i in nums:
            max_val = max(max_val,i)
            dic[i] = dic.setdefault(i,0) + 1
        uniq = range(1,max_val+1)

        dp = [[0] * 2 for _ in uniq]
        #0 : won't pick; 1:pick
        dp[0][0] = 0
        dp[0][1] = uniq[0] * dic.get(uniq[0],0)
        for i in range(1,len(dp)):
            dp[i][0] = max(dp[i-1][0],dp[i-1][1])
            dp[i][1] = dp[i-1][0] + uniq[i] * dic.get(uniq[i],0)
        return max(dp[-1])
原文地址:https://www.cnblogs.com/seyjs/p/11896165.html