Problem
There are N gas stations along a circular route, where the amount of gas at station i is gas[i]
.
You have a car with an unlimited gas tank and it costs cost[i]
of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.
Return the starting gas station’s index if you can travel around the circuit once in the clockwise direction, otherwise return -1.
Note:
- If there exists a solution, it is guaranteed to be unique.
- Both input arrays are non-empty and have the same length.
- Each element in the input arrays is a non-negative integer.
Example 1:
1 |
|
Example 2:
1 |
|
Explanation
-
In order to loop all elements, total gas must equal or greater than total cost, then the
start
can exist. -
If we start from index 0, if current gas is equal or greater than current cost, then we can move forward. After we successfully move forward, we use the remaining gas plus the current gas minus the current cost to get the difference. If the difference is less than 0, that means we cannot start from any indexes between index 0 and current index inclusive. For example, we start from index 0, now when we are on index i, and
curGas + gas[i] - cost[i] < 0
, we know that after index i-1,curGas >= 0
, after index i-2,old_curGas >= 0
, etc. Any index beforei
will only bring positivecurGas
, so if at index i and the difference is negative, then we thestart
cannot be any index between 0 andi
inclusive, so we updatestart = i + 1
. When finish looping, we returnstart
if the total gas is equal or greater than total cost.
Solution
1 |
|