原題地址871. 最低加油次數
汽車從起點出發駛向目的地,該目的地位於出發位置東面 target
英里處。
沿途有加油站,每個 station[i]
代表一個加油站,它位於出發位置東面 station[i][0]
英里處,並且有 station[i][1]
升汽油。
假設汽車油箱的容量是無限的,其中最初有 startFuel
升燃料。它每行駛 1 英里就會用掉 1 升汽油。
當汽車到達加油站時,它可能停下來加油,將所有汽油從加油站轉移到汽車中。
爲了到達目的地,汽車所必要的最低加油次數是多少?如果無法到達目的地,則返回 -1
。
注意:如果汽車到達加油站時剩餘燃料爲 0,它仍然可以在那裏加油。如果汽車到達目的地時剩餘燃料爲 0,仍然認爲它已經到達目的地。
示例 1:
輸入:target = 1, startFuel = 1, stations = []
輸出:0
解釋:我們可以在不加油的情況下到達目的地。
示例 2:
輸入:target = 100, startFuel = 1, stations = [[10,100]]
輸出:-1
解釋:我們無法抵達目的地,甚至無法到達第一個加油站。
示例 3:
輸入:target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]
輸出:2
解釋:
我們出發時有 10 升燃料。
我們開車來到距起點 10 英里處的加油站,消耗 10 升燃料。將汽油從 0 升加到 60 升。
然後,我們從 10 英里處的加油站開到 60 英里處的加油站(消耗 50 升燃料),
並將汽油從 10 升加到 50 升。然後我們開車抵達目的地。
我們沿途在1兩個加油站停靠,所以返回 2 。
提示:
1 <= target, startFuel, stations[i][1] <= 10^9
0 <= stations.length <= 500
0 < stations[0][0] < stations[1][0] < ... < stations[stations.length-1][0] < target
算法
如果剩下的油不足夠去到target,那麼在能到達的加油站選取可以加最大油的,再選擇次大的,依次類推,直到所有能加油的都加了依舊無法到達target或者下一個加油站。
代碼
class Solution:
def minRefuelStops(self, target, startFuel, stations):
"""
:type target: int
:type startFuel: int
:type stations: List[List[int]]
:rtype: int
"""
if startFuel >= target:
return 0
if not stations or sum([j for i, j in stations]) + startFuel < target or startFuel < stations[0][0]:
return -1
left, right, tmp_fuel = 0, target, startFuel
ans = 0
tmp_lst = []
stations.append([target, 0])
for station, fuel in stations:
if tmp_fuel >= right:
return ans
if station <= left + tmp_fuel:
tmp_lst.append(fuel)
else:
tmp_lst.sort()
while len(tmp_lst) and station > left + tmp_fuel:
tmp_fuel += tmp_lst.pop()
ans += 1
if station > left + tmp_fuel:
return -1
tmp_fuel -= station - left
left = station
right = target - station
tmp_lst.append(fuel)
if tmp_fuel >= right:
return ans
return -1