Gas Station
Gas stations stand on a circular road. Station k gives gas[k] units of fuel, and the road from it to the next station takes cost[k]. The car starts at some station with an empty tank. Find the station from which it can drive the whole circle, or return -1 if there is none; if there is one, it is the only one. Our example: gas [4, 3, 1, 5, 2, 4, 1], cost [2, 2, 5, 2, 3, 2, 3] — the answer is 3.
- input
gas,cost: arrays of the same length. Stations stand on a circle; at stationithe car fills upgas[i]units, and driving from it to the next station,i + 1(after the last one, station 0), burnscost[i]. The tank has no limit.- returns
- The index of the station to start from, with an empty tank, to drive once around the circle without running out of gas;
-1if there is none. - constraints
- 1 ≤ gas.length ≤ 3000
- cost.length == gas.length
- 0 ≤ gas[i], cost[i] ≤ 10⁴
- at most one station to start from
- examples
- Open a test in the tests panel: it shows the input and the expected answer.
/**
* @param {number[]} gas
* @param {number[]} cost
* @return {number}
*/
function canCompleteCircuit(gas, cost) {
}
Ctrl ↵
format
reset
saved in this browser
Stuck?
See the solution run step by step on our example, then why it works and its complexity.
Next: more greedy problems
The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.