Topic links: https://leetcode-cn.com/problems/gas-station/
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]
输出: 3
解释:
从 3 号加油站(索引为 3 处)出发,可获得 4 升汽油。此时油箱有 = 0 + 4 = 4 升汽油
开往 4 号加油站,此时油箱有 4 - 1 + 5 = 8 升汽油
开往 0 号加油站,此时油箱有 8 - 2 + 1 = 7 升汽油
开往 1 号加油站,此时油箱有 7 - 3 + 2 = 6 升汽油
开往 2 号加油站,此时油箱有 6 - 4 + 3 = 5 升汽油
开往 3 号加油站,你需要消耗 5 升汽油,正好足够你返回到 3 号加油站。
因此,3 可为起始索引。
Example 2:
输入:
gas = [2,3,4]
cost = [3,4,3]
输出: -1
解释:
你不能从 0 号或 1 号加油站出发,因为没有足够的汽油可以让你行驶到下一个加油站。
我们从 2 号加油站出发,可以获得 4 升汽油。 此时油箱有 = 0 + 4 = 4 升汽油
开往 0 号加油站,此时油箱有 4 - 3 + 2 = 3 升汽油
开往 1 号加油站,此时油箱有 3 - 3 + 3 = 3 升汽油
你无法返回 2 号加油站,因为返程需要消耗 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 toj
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;
}
}