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])
相关推荐
小则又沐风a10 分钟前
类和对象(C++)---上
java·c++·算法
季明洵15 分钟前
动态规划及背包问题
java·数据结构·算法·动态规划·背包问题
busideyang21 分钟前
函数指针类型定义笔记
c语言·笔记·stm32·单片机·算法·嵌入式
Wect23 分钟前
LeetCode 215. 数组中的第K个最大元素:大根堆解法详解
前端·算法·typescript
蒸汽求职23 分钟前
【蒸汽教育求职干货】OPT只剩3个月还没找到工作,怎么办?——留学生IT求职的“紧急预案”
人工智能·经验分享·面试·职场和发展·美国求职
蒸汽求职26 分钟前
【蒸汽教育求职分享】美国IT面试的Behavioral Question:STAR法则人人都知道,但90%的人用错了
人工智能·面试·职场和发展·github·求职招聘·留学生求职
深邃-34 分钟前
数据结构-双向链表
c语言·开发语言·数据结构·c++·算法·链表·html5
2401_8785302135 分钟前
分布式任务调度系统
开发语言·c++·算法
中小企业实战军师刘孙亮37 分钟前
什么是增长陷阱?中小企业“增长陷阱”破局指南-佛山鼎策创局破局增长咨询
职场和发展·新媒体运营·创业创新·需求分析·内容运营
_深海凉_1 小时前
LeetCode热题100-两数之和
算法·leetcode·职场和发展