Gas Station
There are n gas stations on a circular road. Station i holds gas[i] units of fuel, and driving from station i to the next station (station i + 1, or station 0 after the last one) uses cost[i] units.
Your car has an unlimited tank and starts empty at one of the stations. At every station you pick up all of its fuel, then drive on to the next one. The tank must never go below zero on the way.
Return the index of the station from which you can drive all the way around the circle once, ending back where you started. If no station works, return -1. The tests guarantee that when a valid start exists, it is the only one.
Constraints
1 <= n <= 10^5gas.length === cost.length === n0 <= gas[i], cost[i] <= 10^4
Examples
Example 1
Input: gas = [3,1,2,5], cost = [2,4,3,1] Output: 3
Start at station 3: fill 5, drive to station 0 using 1 (4 left). Fill 3 and use 2 (5 left), fill 1 and use 4 (2 left), fill 2 and use 3 (1 left), and you are back at station 3.
Example 2
Input: gas = [2,2,2], cost = [3,3,2] Output: -1
There are 6 units of gas in total but the whole loop costs 8, so no start can work.
Example 3
Input: gas = [4], cost = [3] Output: 0
One station: fill 4 units and spend 3 to drive around back to it.
JavaScript you'll use: Numbers, Math and integer tricks Arrays: create, read, update
/**
* @param {number[]} gas
* @param {number[]} cost
* @return {number}
*/
function canCompleteCircuit(gas, cost) {
}
Ctrl/⌘ + ' runs the examples, Ctrl/⌘ + Enter submits. Use console.log freely: output shows under Console. In the editor, press Esc then Tab to move focus out.