Skip to content

Commit 6391ce7

Browse files
committed
Add Gas Station solution
1 parent 0f9f22e commit 6391ce7

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

arrays/134_Gas_Station/solution.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
def can_complete_circuit(gas: list[int], cost: list[int]) -> int:
2+
"""
3+
Determine the starting gas station's index to travel around a circular route once.
4+
5+
The car starts with an empty tank at one of the gas stations and has an unlimited gas capacity.
6+
It must be able to travel clockwise around all stations, refueling at each, without running out of gas.
7+
8+
:param gas: A list of integers where gas[i] represents the amount of gas at station i.
9+
:param cost: A list of integers where cost[i] represents the gas cost to travel from station i to i+1.
10+
:return: The index of the starting gas station if the circuit can be completed, otherwise -1.
11+
"""
12+
if sum(gas) < sum(cost):
13+
return -1
14+
length = len(gas)
15+
current_tank = 0
16+
start = -1
17+
for index in range(length):
18+
current_tank += gas[index] - cost[index]
19+
if current_tank < 0:
20+
start = -1
21+
current_tank = 0
22+
elif start == -1:
23+
start = index
24+
return start
25+
26+
assert can_complete_circuit(gas=[1, 2, 3, 4, 5], cost=[3, 4, 5, 1, 2]) == 3, 'Test 1 Failed'
27+
assert can_complete_circuit(gas=[2, 3, 4], cost=[3, 4, 3]) == -1, 'Test 2 Failed'
28+
assert can_complete_circuit(gas=[5, 1, 2, 3, 4], cost=[4, 4, 1, 5, 1]) == 4, 'Test 3 Failed'
29+
assert can_complete_circuit(gas=[3, 1, 1], cost=[1, 2, 2]) == 0, 'Test 4 Failed'
30+
assert can_complete_circuit(gas=[1, 2, 3, 4, 5, 5, 70], cost=[2, 3, 4, 3, 9, 6, 2]) == 6, 'Test 5 Failed'

0 commit comments

Comments
 (0)