[LeetCode] 2739. Total Distance Traveled

CNoodle發表於2024-04-25

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;
    }
}

相關文章