LeetCode 871. 最低加油次数

本文详细解析了如何计算汽车从起点到目标地点所需的最低加油次数,通过实例展示了算法的实现过程,包括特殊情况处理和最优加油站选择策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题地址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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值