跳转至

加油站⚓︎

Leetcode题目链接

描述⚓︎

详见中文题目链接

解答⚓︎

class Solution {
public:
    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
        int n = gas.size();
        int len = 0, sum = 0;
        for (int left = 0, right = 0; left < n; left++) {
            while (sum >= 0) {
                if (len == n) return left;

                right = (left + len) % n; len++;
                sum += gas[right] - cost[right];
            }
            len--;
            sum -= gas[left] - cost[left];
        }
        return -1;
    }
};