Skip to content

Commit 5206d59

Browse files
committed
feat: add gas station
1 parent eaa87bd commit 5206d59

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

greedy_methods/gas_station.py

+66
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
"""
2+
Task:
3+
There are n gas stations along a circular route, where the amount of gas
4+
at the ith station is gas[i].
5+
6+
You have a car with an unlimited gas tank and it costs cost[i] of gas
7+
to travel from the ith station to its next (i + 1)th station. You begin the
8+
journey with an empty tank at one of the gas stations.
9+
10+
Given two integer arrays gas and cost, return the starting gas station's index
11+
if you can travel around the circuit once in the clockwise direction,
12+
otherwise return -1. If there exists a solution, it is guaranteed to be unique
13+
14+
Reference: https://leetcode.com/problems/gas-station/description
15+
16+
Implementation notes:
17+
First, check whether the total gas is enough to complete the journey. If not, return -1.
18+
However, if there is enough gas, it is guaranteed that there is a valid
19+
starting index to reach the end of the journey.
20+
Greedily calculate the net gain (gas - cost) at each station.
21+
If the net gain ever goes below 0 while iterating through the stations,
22+
start checking from the next station.
23+
24+
"""
25+
26+
27+
def can_complete_journey(gas: list[int], cost: list[int]) -> int:
28+
"""
29+
This function returns the index from which to start the journey
30+
in order to reach the end.
31+
32+
Args:
33+
gas [list]: Amount of gas available at each station
34+
cost [list]: The cost of gas required to move from a station to the next
35+
36+
Returns:
37+
start [int]: start index needed to complete the journey
38+
39+
Examples:
40+
>>> can_complete_journey([1, 2, 3, 4, 5], [3, 4, 5, 1, 2])
41+
3
42+
>>> can_complete_journey([2, 3, 4], [3, 4, 3])
43+
-1
44+
45+
"""
46+
total_gas = sum(gas)
47+
total_cost = sum(cost)
48+
49+
if total_gas < total_cost:
50+
return -1
51+
52+
start = 0
53+
net = 0
54+
for i in range(len(gas)):
55+
net += gas[i] - cost[i]
56+
if net < 0:
57+
start = i + 1
58+
net = 0
59+
60+
return start
61+
62+
63+
if __name__ == "__main__":
64+
import doctest
65+
66+
doctest.testmod()

0 commit comments

Comments
 (0)