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])
相关推荐
jinmo_C++2 分钟前
Leetcode_59. 螺旋矩阵 II
算法·leetcode·矩阵
夏鹏今天学习了吗3 分钟前
【LeetCode热题100(81/100)】零钱兑换
算法·leetcode·职场和发展
北京地铁1号线12 分钟前
Embedding 模型的经典benchmark:MTEB
算法
焦糖玛奇朵婷19 分钟前
盲盒小程序:开发视角下的功能与体验
java·大数据·jvm·算法·小程序
QiZhang | UESTC32 分钟前
【豆包生成,写项目看】探寻最优学习路径:线性回归从框架补全到从零手写
学习·算法·线性回归
清 澜1 小时前
大模型扫盲式面试知识复习 (二)
人工智能·面试·职场和发展·大模型
知乎的哥廷根数学学派1 小时前
基于多物理约束融合与故障特征频率建模的滚动轴承智能退化趋势分析(Pytorch)
人工智能·pytorch·python·深度学习·算法·机器学习
我是一只小青蛙8882 小时前
位图与布隆过滤器:高效数据结构解析
开发语言·c++·算法
踩坑记录2 小时前
leetcode hot100 238.除了自身以外数组的乘积 medium
leetcode
eso19832 小时前
白话讲述监督学习、非监督学习、强化学习
算法·ai·聚类