[134] 加油站

45 阅读1分钟
/*
 * @lc app=leetcode.cn id=134 lang=javascript
 *
 * [134] 加油站
 */

// @lc code=start
/**
 * @param {number[]} gas
 * @param {number[]} cost
 * @return {number}
 */
var canCompleteCircuit = function (gas, cost) {
  let totalGas = 0,
    totalCost = 0
  // 先计算所需的油量,加油站的总加油量
  for (let i = 0; i < gas.length; i++) {
    totalCost += cost[i]
    totalGas += gas[i]
  }
  // 如果油量小于消耗就return-1
  if (totalCost > totalGas) return -1

  let start = 0,
    currentsGas = 0
  // 初始0减去消耗加上油站的加油
  for (let i = 0; i < gas.length; i++) {
    currentsGas = currentsGas - cost[i] + gas[i]
    if (currentsGas < 0) {
      currentsGas = 0
      // i+1是以下一个油站为起点
      start = i + 1
    }
  }
  return start
}
// @lc code=end