arrays
greedy
There are n gas stations in a circle. Station i gives you gas[i] units of fuel, and driving from station i to station i + 1 (wrapping around at the end) costs cost[i] units. Return the index of the station where you can start with an empty tank and complete the whole circuit exactly once. If it is impossible, return -1.
The canonical interview version guarantees that if a solution exists, it is unique.
Input / output
- Input:
gas: int[],cost: int[] - Output: starting index, or
-1if no full circuit is possible
Examples
gas = [1,2,3,4,5],cost = [3,4,5,1,2]returns3.gas = [2,3,4],cost = [3,4,3]returns-1.gas = [5],cost = [4]returns0.
Constraints
1 <= gas.length == cost.length <= 10^50 <= gas[i], cost[i] <= 10^4
Target complexity
- Aim for
O(n)time andO(1)extra space.
Hints
- First ask whether the total gas is at least the total cost.
- If your running tank becomes negative between
startandi, none of the stations between them can be the answer.
Follow-up Why does the proof of correctness depend on resetting the candidate start only when the running tank becomes negative?
Examples
Example 1
Input: gas = [1,2,3,4,5], cost = [3,4,5,1,2]
Output: 3
Example 2
Input: gas = [2,3,4], cost = [3,4,3]
Output: -1
Example 3
Input: gas = [5], cost = [4]
Output: 0
🔒 6 hidden
Running will execute all 9 cases, including 6 hidden ones.