Problem Description
A truck has two fuel tanks. The main tank holds a certain number of liters of fuel, and the additional tank holds extra fuel. The truck uses fuel at a rate of 10 km per liter. However, every time the truck spends 5 liters from the main tank, if there is at least 1 liter in the additional tank, 1 liter is immediately transferred from the additional tank to the main tank. The problem asks for the maximum distance the truck can travel given the initial fuel quantities.
Key Insights
- The truck travels 10 km per liter, so the basic distance is directly proportional to the liters consumed.
- For every 5 liters consumed from the main tank, if available, 1 liter is refueled from the additional tank. This effectively means that the truck gains an extra liter of fuel (i.e., an extra 10 km) every time 5 liters are consumed.
- The number of times such a fuel injection can occur is limited by both the main tank fuel (after the first liter) and the available additional fuel.
- A mathematical observation leads to a formula: total distance = (mainTank + extraFuelInjections) * 10, where extraFuelInjections = min(additionalTank, (mainTank - 1) // 4).
Space and Time Complexity
Time Complexity: O(1) – The solution uses a constant number of arithmetic operations. Space Complexity: O(1) – Only a few variables are used, independent of the input size.
Solution
We can solve the problem by observing that every 5 liters spent from the main tank can be used to gain an extra liter from the additional tank. However, note that the refuel happens only when the truck has consumed a complete 5 liters of fuel, and the process does not allow partial refills.
The key mathematical insight is that the number of extra liters (i.e., extra fuel injections) received is the minimum of the additional tank fuel and how many times 5 liters can be fully used from the main tank. Since the first liter of the main tank does not trigger an extra refill until after 5 liters, the effective count of possible refuels is (mainTank - 1) // 4. Adding this number to the original mainTank gives the total effective liters, which when multiplied by 10 yields the total distance traveled.
Data Structures and Algorithmic Approach:
- Arithmetic operations with conditional logic using the min() function.
- No need for extra data structures or loops since the formula directly yields the answer.
Gotchas:
- Remember to subtract 1 from the mainTank before division to avoid overcounting extra fuel injections.
- Use integer division to ensure correct counting of complete 5-liter cycles.
Code Solutions
Below are the code solutions in Python, JavaScript, C++, and Java with detailed line-by-line comments.