> For the complete documentation index, see [llms.txt](https://leetcodebook-1.gitbook.io/top-interview-150/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://leetcodebook-1.gitbook.io/top-interview-150/array-string/gas-station.md).

# 加油站

题目链接: <https://leetcode.cn/problems/gas-station>

## 解题思路

1. 遍历数组，计算从第一个加油站开始到下一个加油站消耗的总得汽油数及获得的汽油数，判断是否满足汽油消耗且有剩余
2. 若有则继续，若无则从下一个加油站开始重复步骤1，判断是否能走到底(步骤一已经判断了前一段会导致汽油不足的情况，因此可以直接跳过)

```go
func canCompleteCircuit(gas []int, cost []int) int {
    for i,n:=0,len(gas);i<n;{
        sumGas,sumCost,idx:=0,0,0
        for idx<n{
            j:=(i+idx)%n
            sumGas+=gas[j]
            sumCost+=cost[j]
            if sumCost>sumGas{
                break
            }
            idx++
        }
        if idx==n{
            return i
        }else{
            i+=idx+1
        }
    }
    return -1
}
```

## 复杂度分析

* **时间复杂度：** 对数组进行了双重遍历，因此时间复杂度为 $$O(n^2)$$，其中 $$n$$ 是数组 $$gas$$ 的长度
* **空间复杂度：** 空间复杂度为 $$O(1)$$


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

```
GET https://leetcodebook-1.gitbook.io/top-interview-150/array-string/gas-station.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
