Skip to content

Latest commit

 

History

History
85 lines (63 loc) · 2.11 KB

0740._delete_and_earn.md

File metadata and controls

85 lines (63 loc) · 2.11 KB

740. Delete and Earn

难度: Medium

刷题内容

原题连接

内容描述

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

解题方案

思路 1

典型dp,dp[i]代表的是数字i,然后我们将其变化为删除数字i我们可以得到的最大分数(已经处理过所有比i小的数字了)。

推导公式为dp[i] = max(dp[i]+dp[i-2], dp[i-1]),

  • 即要么删除dp[i]得到所有数字i的和
  • 要么删除dp[i-1]不要dp[i]的分数

又因为Each element nums[i] is an integer in the range [1, 10000],所以dp长度初始化为10001

class Solution(object):
    def deleteAndEarn(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        dp = [0] * 10001
        for num in nums:
            # now dp[num] = sum of the num in nums
            dp[num] += num
        for i in range(2, 10001):
            dp[i] = max(dp[i]+dp[i-2], dp[i-1])
        return dp[-1]

思路 2

迭代

class Solution(object):
    def deleteAndEarn(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        last, now = 0, 0
        for value in range(10001):
            last, now = now, max(last + value * nums.count(value), now)
        return now