MediumPythonJavaScriptTypeScript
Greedy — Gas Station
AlgorithmsGreedyArrays
solve(gas, cost) — there are n stations on a circular route. gas[i] is the fuel
you can take at station i, and cost[i] is the fuel needed to drive from stationi to the next one. You start with an empty tank at one station. Return the index
of the station from which you can complete the whole circuit clockwise, or -1
if no such station exists. If an answer exists it is unique.
Two observations give an O(n) solution: if sum(gas) < sum(cost) the trip is
impossible; otherwise, whenever your tank goes negative at station i, **no
station from the current start up to i can be the answer**, so restart fromi + 1.
Examples
solve([1,2,3,4,5], [3,4,5,1,2]) → 3
solve([2,3,4], [3,4,3]) → -1
solve([5], [4]) → 0
solve([5,1,2,3,4], [4,4,1,5,1]) → 4Sample tests
Test #1Classic example
Input: [[1,2,3,4,5],[3,4,5,1,2]]
Output: 3
Test #2Not enough gas overall
Input: [[2,3,4],[3,4,3]]
Output: -1
Test #3Single station
Input: [[5],[4]]
Output: 0