2019-06-01 17:09:30

**Problem Description:**

**Problem Solving:**

In fact, this is a math problem on nature.

【theorem】

For a loop through the array, if the whole array and SUM> = 0, then there must be found such an element in the array: From this array element, the array around the circle, and has been able to accumulate guarantee for non-negative status.

【prove】

Start from the first and the figures for the middle and there must be a minimum cumulative point, we set x. The final sum> = 0.

Now we are back from the x accumulate, then there must be a non-negative in the state, and to the last site there will be some surplus, and then bound to a negative number does not appear to start from the lowest point x marching.

【Leetcode Discuss】

If sum of all

`gas[i]-cost[i]`

is greater than or equal to`0`

, then there is a start position you can travel the whole circle.

Let`i`

be the index such that the the partial sum

`gas[0]-cost[0]+gas[1]-cost[1]+...+gas[i]-cost[i]`

is the smallest, then the start position should be

`start=i+1`

(`start=0`

if`i=n-1`

). Consider any other partial sum, for example,

`gas[0]-cost[0]+gas[1]-cost[1]+...+gas[i]-cost[i]+gas[i+1]-cost[i+1]`

Since

`gas[0]-cost[0]+gas[1]-cost[1]+...+gas[i]-cost[i]`

is the smallest, we must have

`gas[i+1]-cost[i+1]>=0`

in order for

`gas[0]-cost[0]+gas[1]-cost[1]+...+gas[i]-cost[i]+gas[i+1]-cost[i+1]`

to be greater.

The same reasoning gives that

`gas[i+1]-cost[i+1]>=0 gas[i+1]-cost[i+1]+gas[i+2]-cost[i+2]>=0 ....... gas[i+1]-cost[i+1]+gas[i+2]-cost[i+2]+...+gas[n-1]-cost[n-1]>=0`

What about for the partial sums that wraps around?

`gas[0]-cost[0]+gas[1]-cost[1]+...+gas[j]-cost[j] + gas[i+1]-cost[i+1]+...+gas[n-1]-cost[n-1] >= gas[0]-cost[0]+gas[1]-cost[1]+...+gas[i]-cost[i] + gas[i+1]-cost[i+1]+...+gas[n-1]-cost[n-1] >=0`

The last inequality is due to the assumption that the entire sum of

`gas[k]-cost[k]`

is greater than or equal to 0.

So we have that all the partial sums

`gas[i+1]-cost[i+1]>=0, gas[i+1]-cost[i+1]+gas[i+2]-cost[i+2]>=0, gas[i+1]-cost[i+1]+gas[i+2]-cost[i+2]+...+gas[n-1]-cost[n-1]>=0, ... gas[i+1]-cost[i+1]+...+gas[n-1]-cost[n-1] + gas[0]-cost[0]+gas[1]-cost[1]+...+gas[j]-cost[j]>=0, ...`

Thus

`i+1`

is the position to start.

Therefore, for this question, we can calculate whether the total of gas -? Cost> = 0 If yes, then there must be a solution, in this context, only need to iterate over the array, if you encounter a situation can not be reached, then the it can be calculated from the first can not reach the start again.

public int canCompleteCircuit(int[] gas, int[] cost) { int n = gas.length; int sum = 0; for (int i = 0; i < n; i++) sum += gas[i] - cost[i]; if (sum < 0) return -1; int start = 0; int tank = 0; for (int i = 0; i < n; i++) { tank += gas[i]; if (tank < cost[i]) { start = i + 1; tank = 0; } else { tank -= cost[i]; } } return start; }