Skip to content

Commit e13aeaf

Browse files
authored
Create gas_station.py
1 parent fcf82a1 commit e13aeaf

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

data_structures/arrays/gas_station.py

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
from typing import List
2+
3+
class Solution:
4+
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
5+
total_gas = 0
6+
current_gas = 0
7+
start_station = 0
8+
9+
for i in range(len(gas)):
10+
total_gas += gas[i] - cost[i]
11+
current_gas += gas[i] - cost[i]
12+
13+
# If the current gas goes negative, we cannot start from the previous stations
14+
if current_gas < 0:
15+
start_station = i + 1 # Start from the next station
16+
current_gas = 0 # Reset current gas
17+
18+
# If total gas is negative, we can't complete the circuit
19+
if total_gas < 0:
20+
return -1
21+
else:
22+
return start_station
23+

0 commit comments

Comments
 (0)