Greedy Algorithms8 sections · 316 units
Open in Course

Gas Station - Implementation

The code

function canCompleteCircuit(gas, cost)
 totalSurplus := 0
 currentSurplus := 0
 startStation := 0
 for i from 0 to length of gas - 1
 totalSurplus := totalSurplus + gas[i] - cost[i]
 currentSurplus := currentSurplus + gas[i] - cost[i]
 if currentSurplus < 0 then
 startStation := i + 1
 currentSurplus := 0
 if totalSurplus < 0 then
 return -1
 return startStation

Time: O(n)O(n). Space: O(1)O(1).