-
Medium
-
There are
n
gas stations along a circular route, where the amount of gas at theith
station isgas[i]
.You have a car with an unlimited gas tank and it costs
cost[i]
of gas to travel from theith
station to its next(i + 1)th
station. You begin the journey with an empty tank at one of the gas stations.Given two integer arrays
gas
andcost
, return the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return-1
. If there exists a solution, it is guaranteed to be unique
The idea in this question is that for each step you move, there is always gain ("the amount of gas at the station") and loss("The cost to go to the next station"). Therefore we can solve this problem using dynamic planning by keeping record of how much gas do we have left at each station.
If at any station we saw that we have negative amount of gas, then that means we cannot reach the current station staring from the start we choose in the previous trial. Therefore we will pick the current station to be the start and see if that is valid.
Eventually we would see if we have find a valid starting station or not.
class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
curr=0
n=len(gas)
ans=0
total=0
for i in range(n):
curr=curr+gas[i]-cost[i]
if curr<0:
total+=curr
curr=0
ans=i+1
if curr+total<0:
return -1
return ans