From 21737193f9526c3c1193c9de30368a313f14af17 Mon Sep 17 00:00:00 2001 From: Deven <63876261+devenperez@users.noreply.github.com> Date: Fri, 6 Jan 2023 21:47:30 -0500 Subject: [PATCH] Time: 722 ms (72.46%), Space: 19 MB (90.27%) - LeetHub --- 134-gas-station/134-gas-station.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 134-gas-station/134-gas-station.py diff --git a/134-gas-station/134-gas-station.py b/134-gas-station/134-gas-station.py new file mode 100644 index 0000000..ebc2e4b --- /dev/null +++ b/134-gas-station/134-gas-station.py @@ -0,0 +1,29 @@ +class Solution: + def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: + + # Takes more gas to do a revolution than there is in the stations + if sum(cost) > sum(gas): + return -1 + + n = len(gas) + startingIndex = 0 + while startingIndex < n: + # Attempts to compelete a trip around the stations + currentGasLevel = 0 + for i in range(n): + j = (i + startingIndex) % n + currentGasLevel += gas[j] # Fill up at station j + + currentGasLevel -= cost[j] # Cost to get to station (j+1) + + # Can the car the make it to the next station + if currentGasLevel < 0: + startingIndex = j + 1 + break + + else: + # Only executed if it made a full revolution + return startingIndex + + # Returns if there is no valid index + return -1 \ No newline at end of file