There are N gas stations along a circular route, where the amount of gas at station i is
gas[i]
.
You have a car with an unlimited gas tank and it costs
cost[i]
of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.
Return the starting gas station's index if you can travel around the circuit once, otherwise return -1.
Note:
The solution is guaranteed to be unique.
Solution:The solution is guaranteed to be unique.
If the circuit is possible, i.e. $\sum \text{gas}\geq \sum \text{cost}$. Then once computed the minimum extra gas needed for the circular route, the minimum extra gas if we start on the next position is the same but not counting the previous position.
class Solution: # @param gas, a list of integers # @param cost, a list of integers # @return an integer def canCompleteCircuit(self, gas, cost): minVal = float("inf") minPos = -1 gasTillNow = 0 for i in range(0, len(gas)): gasTillNow += gas[i] - cost[i] if gasTillNow < minVal: minVal = gasTillNow minPos = i if gasTillNow >=0: return (minPos + 1) % len(gas) return -1
No comments :
Post a Comment