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])
相关推荐
让我们一起加油好吗4 小时前
【基础算法】初识搜索:递归型枚举与回溯剪枝
c++·算法·剪枝·回溯·洛谷·搜索
stbomei6 小时前
基于 MATLAB 的信号处理实战:滤波、傅里叶变换与频谱分析
算法·matlab·信号处理
2401_876221346 小时前
Reachability Query(Union-Find)
c++·算法
德先生&赛先生7 小时前
LeetCode-542. 01 矩阵
算法·leetcode·矩阵
HAH-HAH7 小时前
【洛谷】P2197【模板】Nim 游戏
算法·游戏
lichkingyang7 小时前
最近遇到的几个JVM问题
java·jvm·算法
feifeigo1238 小时前
matlab中随机森林算法的实现
算法·随机森林·matlab
躲着人群8 小时前
次短路&&P2865 [USACO06NOV] Roadblocks G题解
c语言·数据结构·c++·算法·dijkstra·次短路
心动啊1219 小时前
支持向量机
算法·机器学习·支持向量机
小欣加油10 小时前
leetcode 1493 删掉一个元素以后全为1的最长子数组
c++·算法·leetcode