Subject description:

Chinese:

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.

English:

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.

class Solution(object): def canCompleteCircuit(self, gas, cost): """ :type gas: List[int] :type cost: List[int] :rtype: int """ if sum(gas) < sum(cost): return -1 n = len(gas) diff = 0 stationIndex = 0 for i in range(n): if gas[i]+diff < cost[i]: stationIndex = i+1; diff = 0 else: diff += gas[i]-cost[i] return stationIndex

Topic Source: stay button