Total Distance Traveled

To calculate the maximum distance traveled by the truck with the given fuel injection rules, we’ll follow these steps:

  1. Initialize a variable distance to keep track of the distance traveled.
  2. While there is fuel in the main tank: a. Determine how much fuel can be consumed from the main tank without needing to inject from the additional tank. b. Calculate the distance that can be covered using that fuel, and update the distance. c. If possible, inject 1 liter from the additional tank to the main tank for every 5 liters consumed. d. Update the main and additional tanks according to the fuel consumed and injected.
  3. Once the main tank is empty, add the distance that can be covered using the remaining fuel in the main tank.
  4. Return the final distance.

Here’s the code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution:
    def distanceTraveled(self, mainTank: int, additionalTank: int) -> int:
        distance = 0

        # Continue while there is fuel in the main tank
        while mainTank > 0:
            # Determine how much fuel can be consumed without needing to inject
            fuel_to_consume = min(mainTank, 5)

            # Calculate distance covered using that fuel
            distance += fuel_to_consume * 10

            # If 5 liters or more were consumed, inject 1 liter from the additional tank
            injections = fuel_to_consume // 5
            fuel_to_inject = min(injections, additionalTank)
            additionalTank -= fuel_to_inject

            # Update the main tank
            mainTank -= fuel_to_consume
            mainTank += fuel_to_inject

        return distance

This code accounts for the injection rules and calculates the maximum distance that can be traveled with the given fuel in the main and additional tanks.