Leetcode 740. Delete and Earn

Problem

You are given an integer array nums. You want to maximize the number of points you get by performing the following operation any number of times:

  • Pick any nums[i] and delete it to earn nums[i] points. Afterwards, you must delete every element equal to nums[i] - 1 and every element equal to nums[i] + 1.

Return the maximum number of points you can earn by applying the above operation some number of times.

Algorithm

Dynamics Programming (DP). F(n) = max(F(n-1), F(n-2)) {if nums[n] exists} else F(n) = F(n-1).

Code

class Solution:
    def deleteAndEarn(self, nums: List[int]) -> int:
        max_value = 0
        for num in nums:
            if max_value < num:
                max_value = num

        flag = [0] * (max_value + 1)
        for num in nums:
            flag[num] += 1
        
        ans = [0] * (max_value + 1)
        ans[1] = flag[1]
        for i in range(2, max_value+1):
            ans[i] = ans[i-1]
            if i > 1 and flag[i] and ans[i] < ans[i-2] + i * flag[i]:
                ans[i] = ans[i-2] + i * flag[i]
        
        return max(ans[max_value], ans[max_value-1])

相关推荐

  1. Leetcode 740. Delete and Earn

    2024-02-21 05:40:01       30 阅读
  2. 动态规划01(leetcode509,70,746

    2024-02-21 05:40:01       7 阅读
  3. leetcode704. 二分查找

    2024-02-21 05:40:01       37 阅读
  4. Leetcode:704. 二分查找

    2024-02-21 05:40:01       45 阅读
  5. LeetCode 704 二分查找

    2024-02-21 05:40:01       18 阅读
  6. Leetcode704_二分查找

    2024-02-21 05:40:01       21 阅读
  7. leetcode 704. 二分查找

    2024-02-21 05:40:01       14 阅读
  8. Leetcode741.摘樱桃

    2024-02-21 05:40:01       11 阅读
  9. Leetcode704_二分查找

    2024-02-21 05:40:01       10 阅读
  10. Leetcode740- 删除并获得点数

    2024-02-21 05:40:01       10 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-02-21 05:40:01       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-02-21 05:40:01       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-02-21 05:40:01       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-02-21 05:40:01       18 阅读

热门阅读

  1. WordPress有没有必要选择付费主题

    2024-02-21 05:40:01       32 阅读
  2. element-plus日期选择器英文改成中文

    2024-02-21 05:40:01       32 阅读
  3. python-adb-getevent转sendevent

    2024-02-21 05:40:01       28 阅读
  4. Message Pack 协议详解及应用

    2024-02-21 05:40:01       35 阅读
  5. redis 主从模式,sentinel 模式配置

    2024-02-21 05:40:01       32 阅读
  6. 2402C++,C++26包索引

    2024-02-21 05:40:01       36 阅读
  7. SpringBoot

    2024-02-21 05:40:01       25 阅读
  8. js遇到的问题 --持续更新

    2024-02-21 05:40:01       30 阅读