Minimum Cost Circular Traversal with Refueling Solution
Problem Statement
You are given two arrays of positive integers: `travelExpenses`, where `travelExpenses[i]` is the amount of fuel consumed to travel from station `i` to station `(i+1) % n`; and `refuelCosts`, where `refuelCosts[i]` is the monetary cost to completely refuel your vehicle at station `i`. You also have an integer `maxCapacity` representing your vehicle's maximum fuel tank capacity. You start at station `0` with `0` fuel. Your objective is to traverse sequentially through all stations from `0` to `n-1` and finally return to station `0`. At each station `i`, before departing for station `(i+1) % n`, you have the option to fully refuel your tank to `maxCapacity` by paying `refuelCosts[i]`. You must always ensure you have enough fuel to complete the next leg of travel. Determine the minimum total monetary cost spent on refueling to complete the entire circular journey. If it's impossible to complete the journey under these conditions, return `-1`.
Examples
Constraints
- `1 <= n <= 10^4`
- `1 <= travelExpenses[i] <= 1000`
- `1 <= refuelCosts[i] <= 1000`
- `1 <= maxCapacity <= 1000`
- `travelExpenses.length == refuelCosts.length == n`
Run, Test & Submit Code
Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.
Solve on Interactive WorkspaceTested Solutions
import sys
def minCost(travelExpenses, refuelCosts, maxCapacity):
n = len(travelExpenses)
dp = [float("inf")] * n
dp[0] = 0
for i in range(n):
for j in range(i + 1, n + i):
totalFuel = 0
for k in range(i, j):
totalFuel += travelExpenses[k % n]
if totalFuel > maxCapacity:
continue
dp[j % n] = min(dp[j % n], dp[i] + refuelCosts[i])
if dp[0] == float("inf"):
return -1
return dp[0]
t = 1
for _ in range(t):
n, maxCapacity = map(int, input().split())
travelExpenses = list(map(int, input().split()))
refuelCosts = list(map(int, input().split()))
print(minCost(travelExpenses, refuelCosts, maxCapacity))