A detailed explanation of leetcode 134: Gas Station
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.
- Both input arrays are non-empty and have the same length
- Each element in the input arrays is a non-negative integer
Input:
gas = [1,2,3,4,5]
cost = [3,4,5,1,2]
Output: 3
We can draw a diagram above to verify the correctness of the output 3.
Now I will show you how to solve the problem and prove the correctness of the algorithm.
Claim 1:
If and only if the following inequality holds there exists a valid answer.
Claim 2:
If the following equation holds, the answer would be j+1. (For the case j is equal to n-1, the answer would be 0. )
Proof:
Suppose the sum of gas[i]-cost[i] is less than 0, then no matter where we start, gas[start]-cost[start]+...+gas[n-1]-cost[n-1]+gas[0]-cost[0]+...+gas[start-1]-cost[start-1], which is equal to Σgas[i]-cost[i], is always less than 0. Thus no matter where we start, we cannot complete one cycle.
Now suppose Σgas[i]-cost[i]>=0, let's examine j in claim 2.
We could deduce that,
gas[0]-cost[0]+...+gas[j]-cost[j]+ gas[j+1]-cost[j+1]>=gas[0]-cost[0]+...+gas[j]-cost[j]
gas[0]-cost[0]+...+gas[j]-cost[j]+ gas[j+1]-cost[j+1]+gas[j+2]-cost[j+2]>=gas[0]-cost[0]+...+gas[j]-cost[j]
...
gas[0]-cost[0]+...+gas[j]-cost[j]+ gas[j+1]-cost[j+1]+...+gas[n-1]-cost[n-1]>=gas[0]-cost[0]+...+gas[j]-cost[j]
therefore,
gas[j+1]-cost[j+1]>=0
gas[j+1]-cost[j+1]+gas[j+2]-cost[j+2]>=0
...
gas[j+1]-cost[j+1]+...+gas[n-1]-cost[n-1]>=0
which means that if we start at (j+1)st station, (j+2)nd station, ..., (n-1)st station, 0th station are all reachable;
we also know that,
gas[0]-cost[0]>=gas[0]-cost[0]+...+gas[j]-cost[j]
gas[0]-cost[0]+gas[1]-cost[1]>=gas[0]-cost[0]+...+gas[j]-cost[j]
...
gas[0]-cost[0]+...+gas[j-1]-cost[j-1]>=gas[0]-cost[0]+...+gas[j]-cost[j]
and
gas[0]-cost[0]+...+gas[j]-cost[j]+ gas[j+1]-cost[j+1]+...+gas[n-1]-cost[n-1]>=0
thus,
gas[j+1]-cost[j+1]+...+gas[n-1]-cost[n-1]+ gas[0]-cost[0]>=0
gas[j+1]-cost[j+1]+...+gas[n-1]-cost[n-1]+ gas[0]-cost[0]+gas[1]-cost[1]>=0
...
gas[j+1]-cost[j+1]+...+gas[n-1]-cost[n-1]+ gas[0]-cost[0]+...+gas[j-1]-cost[j-1]>=0
which means that station 1 to station j are all reachable;
and we know that
gas[j+1]-cost[j+1]+...+gas[n-1]-cost[n-1]+ gas[0]-cost[0]+...+gas[j-1]-cost[j-1] +gas[j]-cost[j]>=0 also holds,
then (j+1)st station is also reachable after one round of travel.