# 134. 加油站

在一条环路上有 N 个加油站，其中第 i 个加油站有汽油 gas\[i] 升。

你有一辆油箱容量无限的的汽车，从第 i 个加油站开往第 i+1 个加油站需要消耗汽油 cost\[i] 升。你从其中的一个加油站出发，开始时油箱为空。

如果你可以绕环路行驶一周，则返回出发时加油站的编号，否则返回 -1。

说明:

* 如果题目有解，该答案即为唯一答案
* 输入数组均为非空数组，且长度相同
* 输入数组中的元素均为非负数。

## 思路

> <https://leetcode-cn.com/problems/gas-station/solution/shi-yong-tu-de-si-xiang-fen-xi-gai-wen-ti-by-cyayc/>

时间复杂度 O(N)，空间复杂度 O(1)。

以该题为例： gas = \[1,2,3,4,5] cost = \[3,4,5,1,2] 下图的黑色折线图即总油量剩余值，若要满足题目的要求：跑完全程再回到起点，总油量剩余值的任意部分都需要在X轴以上，且跑到终点时：总剩余汽油量 >= 0。

为了让黑色折线图任意部分都在X轴以上，我们需要向上移动黑色折线图，直到所有点都在X轴或X轴以上。此时，处在X轴的点即为出发点。即黑色折线图的最低值的位置：index = 3。

![](/files/-M-sTcZFd5xYd-M7nEY5)

**柱状图**\
绿色：可添加的汽油 `gas[i]`\
橙色：消耗的汽油 `cose[i]`

**折线图：**\
虚线（蓝色）：当前加油站的可用值\
实线（黑色）：从`0`开始的`总剩余汽油量`

```javascript
var canCompleteCircuit = function(gas, cost) {
    const len = gas.length
    let spare = 0
    let minSpare = Number.MAX_SAFE_INTEGER
    let minIndex = 0
    for( let i = 0; i < len; i++){
    	spare += gas[i] - cost[i]
      if( spare < minSpare){
      	minSpare = spare
        minIndex = i
      }
    }
    
    return spare < 0 ? -1 : (minIndex + 1) % len
};
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://mm.ricky.moe/algorithm/algorithm-and-data-structure/leetcode/134.-jia-you-zhan.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
