|
1 | | -class Solution: |
2 | | - def can_omplete_circuit(self, gas: list[int], cost: list[int]) -> int: |
3 | | - """ |
4 | | - Finds the starting station index to complete the circuit, |
5 | | - or returns -1 if not possible. |
6 | | - Args: |
7 | | - gas (List[int]): List of gas available at each station. |
8 | | - cost (List[int]): List of gas costs to travel to the next station. |
9 | | - Returns: |
10 | | - int: The index of the starting station, or -1 if no solution exists. |
11 | | - Examples: |
12 | | - >>> solution = Solution() |
13 | | - >>> solution.can_omplete_circuit([1, 2, 3, 4, 5], [3, 4, 5, 1, 2]) |
14 | | - 3 |
15 | | - >>> solution.can_omplete_circuit([2, 3, 4], [3, 4, 3]) |
16 | | - -1 |
17 | | - >>> solution.can_omplete_circuit([5, 1, 2, 3, 4], [4, 4, 1, 5, 1]) |
18 | | - 4 |
19 | | - """ |
20 | | - total_gas = 0 |
21 | | - current_gas = 0 |
22 | | - start_station = 0 |
| 1 | +from typing import NamedTuple |
23 | 2 |
|
24 | | - for i in range(len(gas)): |
25 | | - total_gas += gas[i] - cost[i] |
26 | | - current_gas += gas[i] - cost[i] |
27 | 3 |
|
28 | | - if current_gas < 0: |
29 | | - start_station = i + 1 |
30 | | - current_gas = 0 |
| 4 | +class GasStation(NamedTuple): |
| 5 | + gas: int # Amount of gas available at this gas station |
| 6 | + cost: int # Cost of gas required to drive to the next station |
31 | 7 |
|
32 | | - if total_gas < 0: |
33 | | - return -1 |
34 | | - else: |
35 | | - return start_station |
| 8 | + |
| 9 | +def can_complete_circuit(gas_stations: list[GasStation]) -> int: |
| 10 | + """ |
| 11 | + Finds the starting station index to complete the circuit, |
| 12 | + or returns -1 if not possible. |
| 13 | + Args: |
| 14 | + gas_stations (List[GasStation]): List of gas stations with gas and cost attributes. |
| 15 | + Returns: |
| 16 | + The index of the starting station, or -1 if no solution exists. |
| 17 | + Examples: |
| 18 | + >>> GS = GasStation |
| 19 | + >>> test_stations = ( |
| 20 | + ... [GS(1, 3), GS(2, 4), GS(3, 5), GS(4, 1), GS(5, 2)], |
| 21 | + ... [GS(2, 3), GS(3, 4), GS(4, 3)], |
| 22 | + ... [GS(5, 4), GS(1, 4), GS(2, 1), GS(3, 5), GS(4, 1)] |
| 23 | + ... ) |
| 24 | + >>> can_complete_circuit(test_stations[0]) |
| 25 | + 3 |
| 26 | + >>> can_complete_circuit(test_stations[1]) |
| 27 | + -1 |
| 28 | + >>> can_complete_circuit(test_stations[2]) |
| 29 | + 4 |
| 30 | + """ |
| 31 | + total_gas = sum(station.gas - station.cost for station in gas_stations) |
| 32 | + current_gas: int = 0 |
| 33 | + start_station = 0 |
| 34 | + for i, gas_station in enumerate(gas_stations): |
| 35 | + needed_gas = gas_station.gas - gas_station.cost |
| 36 | + total_gas += needed_gas |
| 37 | + current_gas += needed_gas |
| 38 | + if current_gas < 0: |
| 39 | + start_station = i + 1 |
| 40 | + current_gas = 0 |
| 41 | + if total_gas < 0: |
| 42 | + return -1 |
| 43 | + return start_station |
36 | 44 |
|
37 | 45 |
|
38 | 46 | # Example usage with doctests |
|
0 commit comments