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])
相关推荐
courniche32 分钟前
ECDH、ECDHE、ECDLP、ECDSA傻傻分不清?
算法·密码学
前端小刘哥43 分钟前
超低延迟与高并发:视频直播点播平台EasyDSS在游戏直播场景的技术实践
算法
毅炼1 小时前
常见排序算法
java·算法·排序算法
猫梦www1 小时前
力扣21:合并两个有序链表
数据结构·算法·leetcode·链表·golang·力扣
Han.miracle1 小时前
数据结构——排序的学习(一)
java·数据结构·学习·算法·排序算法
爱coding的橙子1 小时前
每日算法刷题Day76:10.19:leetcode 二叉树12道题,用时3h
算法·leetcode·职场和发展
liu****3 小时前
20.哈希
开发语言·数据结构·c++·算法·哈希算法
夏鹏今天学习了吗3 小时前
【LeetCode热题100(47/100)】路径总和 III
算法·leetcode·职场和发展
smj2302_796826523 小时前
解决leetcode第3721题最长平衡子数组II
python·算法·leetcode
m0_626535204 小时前
力扣题目练习 换水问题
python·算法·leetcode