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])
相关推荐
YLCHUP27 分钟前
【括号匹配+dp优化】题解:双端括号(brackets)_动态规划_状态优化_数学建模_贪心_性质挖掘_STLmap_C++算法竞赛
数据结构·c++·笔记·算法·数学建模·贪心算法·动态规划
郝学胜-神的一滴1 小时前
Effective STL 条款09:慎重选择删除元素的方法
开发语言·网络·数据结构·c++·算法·stl
geovindu5 小时前
python:Logistic Regression
开发语言·后端·python·算法
geovindu7 小时前
python: Random Forest
开发语言·后端·python·算法·随机森林
.道阻且长.7 小时前
Linux基础IO:理解文件以及回顾C文件接口
linux·运维·服务器·c语言·开发语言·职场和发展
凌冰_8 小时前
数据结构 - 线性结构(三)
java·数据结构·算法·软件工程
拂拉氏8 小时前
【知识讲解】 数据结构与算法-树状数组的认识
数据结构·算法·树状数组
技术管理手帐8 小时前
【质量管理】FMEA 不是填表游戏:DFMEA 与 PFMEA 的正确打开方式
程序人生·职场和发展·软件工程·创业创新·敏捷流程
饮水桶_T10 小时前
C++ STL00 | 六大核心组件协作框架 笔记
开发语言·算法·百度·facebook·新浪微博