当前位置:网站首页>《LC刷题总结》——贪心
《LC刷题总结》——贪心
2022-08-09 01:11:00 【Weiyaner】
关于贪心
贪心解法没有固定的模板。只有一个感觉。
如果能实现每一阶段局部最优,就可以拓展到全局,得到最优解。
贪心算法一般分为如下四步:
- 将问题分解为若干个子问题
- 找出适合的贪心策略
- 求解每一个子问题的最优解
- 将局部最优解堆叠成全局最优解
53. 最大子序和
122. 买卖股票的最佳时机 II
题目:
可以无限次的买卖股票,获取的最大利润。同一天可以买卖各一次。
思路:
考虑贪心的思路,可以计算相邻两天买卖的利润,然后取所有的正利润即可。
代码:
res = 0
for i in range(1,len(prices)):
if prices[i]-prices[i-1] > 0:
res += prices[i]-prices[i-1]
return res
55. 跳跃游戏
题目:
数组中的每个元素代表你在该位置可以跳跃的最大长度。
判断你是否能够到达最后一个下标。
思路:
贪心思路,每更新一次index,都计算一次最大的覆盖范围,这个cover可能没变化,也可能是index+nums[i]的值。看cover是否能到最后一个数字。
代码:
class Solution:
def canJump(self, nums: List[int]) -> bool:
index, cover = 0, 0
while index <= cover:
cover = max(cover, index+nums[index])
if cover >= len(nums)-1:
print(index,cover)
return True
index += 1
return False
边栏推荐
- Using MySQL on Windows: Automatic Scheduled Backups
- 【C语言刷题】链表中快慢指针的应用
- 知识图谱学习笔记——我的第一次知识图谱实践
- MySQL存储过程与函数
- 在Windows环境下使用MySQL:自动定时备份
- String compression
- 使用jdbc来处理MySQL的utf8mb4字符集(转)
- js文件的处理
- Docker redis master-slave replication setup, the container cannot be started?
- 在Ubuntu/Linux环境下使用MySQL:解决com.mysql.jdbc.PacketTooBigException: Packet for query is too large的问题
猜你喜欢
Using MySQL in Ubuntu/Linux environment: Modify the database sql_mode to solve the "this is incompatible with sql_mode=only_full_group_by" problem
统一身份管理平台IAM单点登录流程及第三方接口设计方案
clickhouse 思维导图
微信企业号开发之获取AccessToken
4-11 Matplotlib 配置
ONNX是什么?怎么用?[简明解读版]
【Fiddler】Fiddler实现mock测试(模拟接口数据)
Using MySQL on Windows: Automatic Scheduled Backups
5-3 Seaborn 分布绘图
Non-major graduates, five-faced Ali: Four rounds of technical + HR have already taken an offer
随机推荐
全新Swagger3.0教程,OAS3快速配置指南,实现API接口文档自动化!
使用jdbc来处理MySQL的utf8mb4字符集(转)
String compression
4-4 Matplotlib库 直方图
Early departure, learning source half a year, finally got the ants Offer to share the interview process
WPF效果第一百九十四篇之伸缩面板
OIDC 思维导图
观察者模式
5-5 Seaborn库FacetGrid结构图
【科研-学习-pytorch】1-框架特性和常见问题类型
Using MySQL in Ubuntu/Linux environment: Modify the database sql_mode to solve the "this is incompatible with sql_mode=only_full_group_by" problem
ffplay播放控制
ONNX是什么?怎么用?[简明解读版]
Sencha Touch页面跳转创建返回上一级按钮的设计思路
Sencha Touch页面跳转创建返回上一级按钮的设计思路
Sencha Touch延迟加载模块提高程序启动时性能
【科研-学习-pytorch】4-数据类型、创建、索引和维度变化
字符串压缩
【科研-学习-pytorch】2-线性回归
Using MySQL in Ubuntu/Linux environment: Solve the problem of com.mysql.jdbc.PacketTooBigException: Packet for query is too large