LetCode 134. 加油站

class Solution {
public:
    int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
        int start = 0; // 起始位置
        int remain = 0; // 当前剩余燃料
        int debt = 0; // 前半段走的路途超过的油量

        for (int i = 0; i < gas.size(); i++) {
            remain += gas[i] - cost[i];
            if (remain < 0) {
                debt += remain;
                start = i + 1;
                remain = 0;
            }
        }
        // 如果后半段剩余的油量加上前半段超过的油量大于等于0,说明能到
        return remain + debt >= 0 ? start : -1;
    }
};

static int x=[](){
    std::ios::sync_with_stdio(false);
    cin.tie(NULL);
    return 0;
}();

猜你喜欢

转载自blog.csdn.net/wbb1997/article/details/81123599