134.加油站

加油站

在一条环路上有 n 个加油站,第 i 个加油站有汽油 gas[i] 升。从第 i 个加油站开往第 i+1 个加油站需要消耗汽油 cost[i] 升。你的油箱容量无限,开始时油箱为空。给定两个整数数组 gas 和 cost,如果你可以按顺序绕环路行驶一周,则返回出发时加油站的编号,否则返回 -1。

解析

1
2
3
4
5
6
7
8
9
10
var canCompleteCircuit = function (gas, cost) {
let totalTank = 0, currTank = 0, start = 0;
for (let i = 0; i < gas.length; i++) {
const diff = gas[i] - cost[i];
totalTank += diff;
currTank += diff;
if (currTank < 0) { start = i + 1; currTank = 0; }
}
return totalTank >= 0 ? start : -1;
};

134.加油站
https://leetcode.lz5z.com/134.gas-station/
作者
tickli
发布于
2024年4月7日
许可协议