Skip to content

Commit b8cb2fa

Browse files
authored
Added gas_station.py
1 parent fcf82a1 commit b8cb2fa

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

data_structures/arrays/gas_station.py

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
from typing import List
2+
3+
class Solution:
4+
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
5+
# Step 1: Initialize variables
6+
# total_gas will keep track of the total balance of gas - cost across all stations
7+
# current_gas will track the gas balance for the current trip from the starting station
8+
# start_station will track the potential starting point of the circuit
9+
total_gas = 0
10+
current_gas = 0
11+
start_station = 0
12+
13+
# Step 2: Loop through each gas station
14+
for i in range(len(gas)):
15+
# Calculate the net gas gain/loss at the current station
16+
total_gas += gas[i] - cost[i]
17+
current_gas += gas[i] - cost[i]
18+
19+
# Step 3: If current_gas becomes negative, it means we cannot continue
20+
# the journey from the current start_station, so we update the start_station
21+
# to the next one and reset the current_gas to 0.
22+
if current_gas < 0:
23+
start_station = i + 1 # Move the starting station to the next one
24+
current_gas = 0 # Reset the gas for the new start
25+
26+
# Step 4: Check if the total gas is enough to complete the circuit
27+
# If total_gas is negative, it means the entire circuit cannot be completed
28+
if total_gas < 0:
29+
return -1
30+
else:
31+
# If total_gas is non-negative, return the start_station as the answer
32+
return start_station

0 commit comments

Comments
 (0)