134. Gas Station
Read the full problem statement on LeetCode.
Difficulty: medium Acceptance: 46% Topics: Array, Greedy
View full problem on LeetCode Reading material
Reference solution (spoiler · python)
# Time: O(n)
# Space: O(1)
class Solution(object):
# @param gas, a list of integers
# @param cost, a list of integers
# @return an integer
def canCompleteCircuit(self, gas, cost):
start, total_sum, current_sum = 0, 0, 0
for i in xrange(len(gas)):
diff = gas[i] - cost[i]
current_sum += diff
total_sum += diff
if current_sum < 0:
start = i + 1
current_sum = 0
if total_sum >= 0:
return start
return -1
Solution from kamyu104/LeetCode-Solutions · MIT
Similar questions