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 numsi and delete it to earn numsi points. Afterwards, you must delete every element equal to numsi - 1 and every element equal to numsi + 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 numsn 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])
相关推荐
晊晌_h4 小时前
嵌入式从0到精通——数据结构总结[特殊字符]
数据结构·算法·排序算法
我找到地球的支点啦5 小时前
Matlab系列(009) 一CRC循环冗余校验详解
开发语言·数据结构·算法·matlab·信息与通信
罗西的思考5 小时前
【OpenClaw具身硬件】ZeroClaw 源码阅读笔记(3)--- RAG
人工智能·算法·机器学习
浪里镖客6 小时前
位姿转换矩阵写法-个人习惯(计算机理解其实是相反的)
线性代数·算法·矩阵
丰锋ff6 小时前
面试问题合集
面试·职场和发展
颜挺锐6 小时前
如何轻松通过性能测试之第四篇:性能测试项目怎么交付?一文讲透九步实施流程(附面试话术 + 实战清单)
面试·职场和发展
小白羊丨9 小时前
如何诊断 Prompt 模板导致的效果下降?
人工智能·算法·prompt
OPEN-F10 小时前
C++11/14新特性精讲:移动语义与智能指针实战
开发语言·c++·算法
lisin-lee-cooper10 小时前
【leetcode658】有序数组找出k个最接近x的数
java·数据结构·算法
sunburn-10 小时前
Java堆(Heap)详解与实战教学
java·开发语言·数据结构·ide·算法