当前位置:网站首页>leetcode:871. 最低加油次数【以前pat做过 + 最大堆 +贪心】
leetcode:871. 最低加油次数【以前pat做过 + 最大堆 +贪心】
2022-07-03 00:46:00 【白速龙王的回眸】

分析
注意,加油站是沿途,所以target一定在所有加油站的右方
然后,油的效果是累计的,根跳跃游戏不一样,不能走一下贪心一下
要用一个大根堆维护之前的加油中最大的加油量来贪心
思想就是,走到某个地方,如果去到之后的油是负数,那么就找之前存着的加油站中的最大值加一下,计算一次
如果加完之前的所有都到不了就凉凉
然后把当前的加油站放入大根堆(奖励),并更新上一个点prev
注意,target是最后一个curr,也要算上去
Ac code
class Solution:
def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int:
# 加油的效果是累计的
# 所以用大根堆,每次取最大的加油来贪心(大根堆)
# 如果取完还不能到目前点,返回-1
ans, nowFuel, prev, pq = 0, startFuel, 0, []
stations.sort()
n = len(stations)
# 多一个target的位置
# 沿途右加油站,所以target一定在最右边
for i in range(n + 1):
# 当前要去的位置
curr = stations[i][0] if i < n else target
nowFuel -= curr - prev
# 不够油的,贪心加油
while nowFuel < 0 and pq:
nowFuel += -heappop(pq)
ans += 1
# 加完开始去不到
if nowFuel < 0:
return -1
# 若能去到,放进大根堆
if i < n:
heappush(pq, -stations[i][1])
# 更新prev
prev = curr
return ans
总结
贪心 + 大根堆
非常classic
边栏推荐
- leetcode-849:到最近的人的最大距离
- excel IF公式判断两列是否相同
- [introduction to AUTOSAR seven tool chain]
- [AUTOSAR + IO Architecture]
- 拥抱平台化交付的安全理念
- [AUTOSAR eight OS]
- [AUTOSAR twelve mode management]
- The difference between tail -f, tail -f and tail
- Overlay of shutter (Pop-Up)
- [case sharing] let the development of education in the new era advance with "number"
猜你喜欢
随机推荐
(C language) data storage
leetcode-241:为运算表达式设计优先级
[flutter] icons component (load the built-in icon of flutter | display the material design icon completely)
How to convert Quanzhi a40i/t3 to can through SPI
指针进阶(一)
【AutoSAR 三 RTE概述】
Leetcode-934: the shortest Bridge
Leetcode-849: maximum distance to the nearest person
飞凌搭载TI AM62x的ARM核心板/开发板首发上市,亮相Embedded World 2022
[shutter] image component (configure local GIF image resources | load placeholder with local resources)
leetcode-224:基本计算器
图解网络:什么是虚拟路由器冗余协议 VRRP?
百度智能云牵头打造智能云综合标准化平台
Vulkan-性能及精细化
[C language] branch and loop statements (Part 1)
Web2.0的巨头纷纷布局VC,Tiger DAO VC或成抵达Web3捷径
Deep analysis of data storage in memory
leetcode-849:到最近的人的最大距离
The arm core board / development board of Feiling equipped with Ti am62x made its debut in embedded world 2022
[AUTOSAR nine c/s principle Architecture]



![[case sharing] let the development of education in the new era advance with](/img/11/af88d16dc66f00840cbfc5ba5d68bd.jpg)


![[overview of AUTOSAR four BSW]](/img/19/c2273bbedb7f8d859e5a3805ed5740.png)


