当前位置:网站首页>《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
边栏推荐
- 深度学习模型的两种部署:ONNX与Caffe
- Unified identity management platform IAM single sign-on process and third-party interface design scheme
- 微信企业号开发之获取AccessToken
- 一名双非程序媛面试蚂蚁、美团、携程等大厂拿 offer 分享面试过程
- 4-7 Matplotlib库 箱线图
- JD.com was abused on three sides. Regarding redis, high concurrency, and distributed, I am confused.
- 4-6 Matplotlib库 饼图
- Wireshark抓包工具
- d初化模板构造器
- 【Seata】分布式事务Seata入门与实战
猜你喜欢

4-6 Matplotlib库 饼图

在实际工作中如何开展性能测试?

椭圆曲线复习

A double non-programmer interviewed Ant, Meituan, Ctrip and other big companies with offers to share the interview process

4-5 Matplotlib库 散点图

5-3 Seaborn 分布绘图

Proe/Creo智能硬件产品结构设计要点「干货分享」

【图像去噪】基于边缘增强扩散 (cEED) 和 Coherence Enhancing Diffusion (cCED) 滤波器实现图像去噪附matlab代码

PostMan导入证书 添加证书

远程控制项目遇到的bug
随机推荐
The Best Open Source Web Application Firewall to Protect Your Web Applications
如何在EasyDSS中使用ffmpeg实现点播视频的拼接与合成?
【科研-学习-pytorch】2-线性回归
tf.pad()--填充操作
makefile file compilation
理财产品募集期和开放期有什么区别?
clickhouse 思维导图
5-1 Seaborn 关系绘图
[Cellular Automata] Simulation of emergency evacuation of disaster personnel under social force factors based on cellular automata with matlab code attached
2022年中国全民健身发展白皮书
在vscode中编辑、编译、下载Keil工程
DataNode重启
生成一系列随机字符串的文件
『Another Redis DeskTop Manager』用了这款Redis可视化工具,分析效率提升12倍
【科研-学习-pytorch】5-boardcasting、合并分割
观察者模式
字符串压缩
Use Ehcache distributed cache to easily create commercial-grade high-concurrency, high-performance API interfaces!
MySQL存储过程与函数
微信企业号开发之获取AccessToken