/** * https://leetcode.cn/problems/gas-station/?envType=study-plan-v2&envId=top-interview-150 * @param {number[]} gas * @param {number[]} cost * @return {number} */ const canCompleteCircuit = function (gas, cost) { let totalGas = 0; let totalCost = 0; let currentGas = 0; let start = 0; for (let i = 0; i < gas.length; i++) { totalGas += gas[i]; totalCost += cost[i]; currentGas += gas[i] - cost[i]; // 如果油量不足,更新起点为下一个加油站 if (currentGas < 0) { start = i + 1; currentGas = 0; } } // 如果总油量小于总油耗,无法完成一圈 return totalGas < totalCost ? -1 : start; };