diff --git a/134-Gas-Station.py b/134-Gas-Station.py index a33d8e773..1fb6df44d 100644 --- a/134-Gas-Station.py +++ b/134-Gas-Station.py @@ -1,14 +1,15 @@ class Solution: def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: - start, end = len(gas) - 1, 0 - total = gas[start] - cost[start] + if sum(gas) < sum(cost): + return -1 + + res = 0 + total = 0 + for i in range(len(gas)): + total += gas[i] - cost[i] + + if total < 0: + total = 0 + res = i + 1 - while start >= end: - while total < 0 and start >= end: - start -= 1 - total += gas[start] - cost[start] - if start == end: - return start - total += gas[end] - cost[end] - end += 1 - return -1 + return res diff --git a/python/134-Gas-Station.py b/python/134-Gas-Station.py index a33d8e773..1fb6df44d 100644 --- a/python/134-Gas-Station.py +++ b/python/134-Gas-Station.py @@ -1,14 +1,15 @@ class Solution: def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: - start, end = len(gas) - 1, 0 - total = gas[start] - cost[start] + if sum(gas) < sum(cost): + return -1 + + res = 0 + total = 0 + for i in range(len(gas)): + total += gas[i] - cost[i] + + if total < 0: + total = 0 + res = i + 1 - while start >= end: - while total < 0 and start >= end: - start -= 1 - total += gas[start] - cost[start] - if start == end: - return start - total += gas[end] - cost[end] - end += 1 - return -1 + return res