## Subject description:

There are N stations in a loop, wherein the i-th gasoline stations Gas [i] l.

You have an unlimited capacity of the fuel tank car, from the i-th gas station bound for the first i + 1 gas stations need to consume gasoline cost [i] liter. You start from a gas station where, at the start of the fuel tank is empty.

If you can travel around the ring a week starting when the number of gas stations is returned, otherwise -1.

Description:

• If the title has a solution, the answer is the only answer.
• Input array are non-empty array, and the same length.
• Enter the array elements are non-negative.

## Example:

Example 1:

``````输入:
gas  = [1,2,3,4,5]
cost = [3,4,5,1,2]

Example 2:

``````输入:
gas  = [2,3,4]
cost = [3,4,3]

## Ideas:

From `i`the `j`position, there is `sum(gas) < sum(cost)`described `i`to not `j`, and `i`to `j`between any locations are not to`j`

You can see proof of official explanations

``````class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
if sum(gas) < sum(cost):return -1
res = 0
tank = 0
for i, item in enumerate(zip(gas, cost)):
tank += (item[0] - item[1])
if tank < 0:
res = i + 1
tank = 0
return res``````

java

``````class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int sum = 0;
for (int i = 0; i < gas.length; i++) sum += (gas[i] - cost[i]);
if (sum < 0) return -1;
int tank = 0;
int res = 0;
for (int i = 0; i < gas.length; i++) {
tank += (gas[i] - cost[i]);
if (tank < 0) {
res = i + 1;
tank = 0;
}
}
return res;
}
}``````

### Guess you like

Origin www.cnblogs.com/powercai/p/11202989.html
Recommended
Ranking
Daily