Skip to content

Commit 4e61194

Browse files
committed
Add problem 134 - Gas Station
1 parent 30d6527 commit 4e61194

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

problems/greedy/gas_station.py

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
from typing import List
2+
3+
4+
class GasStation:
5+
@staticmethod
6+
def canCompleteCircuit(gas: List[int], cost: List[int]) -> int:
7+
# Local effective fuel - fuel if we start from current index
8+
local_fuel = 0
9+
# Global effective fuel - fuel left after the journey
10+
global_fuel = 0
11+
# Index to start the journey from
12+
index = 0
13+
# Process the arrays
14+
for i in range(len(gas)):
15+
local_fuel += gas[i] - cost[i]
16+
global_fuel += gas[i] - cost[i]
17+
# Check if the fuel becomes negative
18+
if local_fuel < 0:
19+
local_fuel = 0
20+
index = i + 1
21+
return index if global_fuel >= 0 else -1

tests/greedy/gas_station_test.py

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import unittest
2+
3+
from problems.greedy.gas_station import GasStation
4+
5+
6+
class TestGasStation(unittest.TestCase):
7+
8+
def test_can_complete_circuit_basic(self):
9+
gas_station = GasStation()
10+
gas = [1, 2, 3, 4, 5]
11+
cost = [3, 4, 5, 1, 2]
12+
self.assertEqual(gas_station.canCompleteCircuit(gas, cost), 3)
13+
14+
def test_can_complete_circuit_no_solution(self):
15+
gas_station = GasStation()
16+
gas = [2, 3, 4]
17+
cost = [3, 4, 5]
18+
self.assertEqual(gas_station.canCompleteCircuit(gas, cost), -1)
19+
20+
def test_can_complete_circuit_single_station(self):
21+
gas_station = GasStation()
22+
gas = [5]
23+
cost = [4]
24+
self.assertEqual(gas_station.canCompleteCircuit(gas, cost), 0)
25+
26+
def test_can_complete_circuit_all_stations_equal(self):
27+
gas_station = GasStation()
28+
gas = [1, 1, 1, 1]
29+
cost = [1, 1, 1, 1]
30+
self.assertEqual(gas_station.canCompleteCircuit(gas, cost), 0)
31+
32+
def test_can_complete_circuit_multiple_solutions(self):
33+
gas_station = GasStation()
34+
gas = [2, 3, 4]
35+
cost = [2, 1, 2]
36+
self.assertEqual(gas_station.canCompleteCircuit(gas, cost), 0) # Returns the first valid start
37+
38+
39+
if __name__ == '__main__':
40+
unittest.main()

0 commit comments

Comments
 (0)