[LeetCode] 2739. Total Distance Traveled

A truck has two fuel tanks. You are given two integers, mainTank representing the fuel present in the main tank in liters and additionalTank representing the fuel present in the additional tank in liters.

The truck has a mileage of 10 km per liter. Whenever 5 liters of fuel get used up in the main tank, if the additional tank has at least 1 liters of fuel, 1 liters of fuel will be transferred from the additional tank to the main tank.

Return the maximum distance which can be traveled.

Note: Injection from the additional tank is not continuous. It happens suddenly and immediately for every 5 liters consumed.

Example 1:
Input: mainTank = 5, additionalTank = 10
Output: 60
Explanation:
After spending 5 litre of fuel, fuel remaining is (5 - 5 + 1) = 1 litre and distance traveled is 50km.
After spending another 1 litre of fuel, no fuel gets injected in the main tank and the main tank becomes empty.
Total distance traveled is 60km.

Example 2:
Input: mainTank = 1, additionalTank = 2
Output: 10
Explanation:
After spending 1 litre of fuel, the main tank becomes empty.
Total distance traveled is 10km.

Constraints:
1 <= mainTank, additionalTank <= 100

总行驶距离。

卡车有两个油箱。给你两个整数,mainTank 表示主油箱中的燃料(以升为单位),additionalTank 表示副油箱中的燃料(以升为单位)。

该卡车每耗费 1 升燃料都可以行驶 10 km。每当主油箱使用了 5 升燃料时,如果副油箱至少有 1 升燃料,则会将 1 升燃料从副油箱转移到主油箱。

返回卡车可以行驶的最大距离。

注意:从副油箱向主油箱注入燃料不是连续行为。这一事件会在每消耗 5 升燃料时突然且立即发生。

思路

题意不难理解,但是这道题通过率很低,我想是因为很多人忽略了一个细节,就是当 mainTank 烧了 5 升燃料的时候,会获得 1 升燃料的补偿,此时虽然跑了 50 km,但是对于 mainTank 来说,实际只消耗了 4 升燃料。所以为了求我们从 additionalTank 获得了多少燃料的补偿,并不是简单用 mainTank / 5 即可。

这里我注意到,在 mainTank 初始值在一定范围内的时候,他获得补偿的次数是有规律的。比如
mainTank 在 1 - 4 之间的时候,补偿了 0 次
mainTank 在 5 - 9 之间的时候,补偿了 1 次
mainTank 在 10 - 14 之间的时候,补偿了 2 次
mainTank 在 15 - 19 之间的时候,补偿了 3 次

所以卡车一共可以获得的补偿次数 = (mainTank - 1) / 4。想通了这一点,剩下的内容就很简单了。当然这道题也可以用 while 循环做,但是如果数据量太大容易超时。

复杂度

时间O(1)
空间O(1)

代码

Java实现

class Solution {
    public int distanceTraveled(int mainTank, int additionalTank) {
        int res = 0;
        int times = (mainTank - 1) / 4;
        mainTank += Math.min(additionalTank, times);
        res = 10 * mainTank;
        return res;
    }
}
posted @ 2024-04-25 04:47  CNoodle  阅读(11)  评论(0编辑  收藏  举报