MCPcopy Create free account
hub / github.com/ByteByteGoHq/coding-interview-patterns / gas_stations

Function gas_stations

python3/Greedy/gas_stations.py:4–19  ·  view source on GitHub ↗
(gas: List[int], cost: List[int])

Source from the content-addressed store, hash-verified

2
3
4def gas_stations(gas: List[int], cost: List[int]) -> int:
5 # If the total gas is less than the total cost, completing the
6 # circuit is impossible.
7 if sum(gas) < sum(cost):
8 return -1
9 start = tank = 0
10 for i in range(len(gas)):
11 tank += gas[i] - cost[i]
12 # If our tank has negative gas, we cannot continue through the
13 # circuit from the current start point, nor from any station
14 # before or including the current station 'i'.
15 if tank < 0:
16 # Set the next station as the new start point and reset the
17 # tank.
18 start, tank = i + 1, 0
19 return start

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected