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

python3 复制代码
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])
相关推荐
多米Domi0116 分钟前
0x3f第14天 最长公共子序列
算法·深度优先
spssau9 分钟前
正交试验设计全解析:从正交表生成到极差与方差分析
数据库·算法·机器学习
minhuan21 分钟前
大模型应用:不减性能只减负担:大模型稀疏化技术全景与实践.36
大数据·人工智能·算法
爱学大树锯40 分钟前
592 · 查找和替换模式
算法
爱学大树锯1 小时前
775 · 回文对
算法
girl-07261 小时前
2025.12.26代码分析
数据结构·算法
大罗辑1 小时前
2026软考备考刷题:软件设计师经典100题(5)含详细解析
算法·软考·软件设计师·2026软考·软设备考
咕噜企业分发小米1 小时前
阿里云Milvus支持哪些向量检索算法?
算法·机器学习·milvus
蒙奇D索大1 小时前
【数据结构】排序算法精讲|折半插入排序全解:高效优化、性能对比、实战剖析
数据结构·学习·考研·算法·排序算法·改行学it
汽车仪器仪表相关领域1 小时前
ZDT-III 通用电机测试系统
数据库·算法·单元测试·压力测试·可用性测试