Gamified challenge · Greedy elimination
Stations 0 to n − 1 sit on a ring road. At station i the car can fill up gas[i] fuel, and driving on to station i + 1 (station 0 after the last) burns cost[i]. The tank starts empty and has no limit; it must never go below zero.
Write startStation(gas, cost) that returns a station from which the car can drive once all the way round, or -1 if there is none. If several stations work, any of them is accepted.
For gas = [1, 2, 3, 4, 5], cost = [3, 4, 5, 1, 2] the answer is 3: the tank reads 3, 6, 4, 2, 0 after each leg.
This game is part of the paid plans. Sign in, then pick a plan to write your answer, watch it play out, and step through the algorithm with its guide.
Sign in with Google