// 演算法 / Algorithm:
// 一次線性掃描，維護 total（全程淨油量）與 tank（目前候選段的淨油量）。
// 每當 tank 變負，代表此段任何站都不能當起點，把起點重設為下一站、tank 歸零。
// 結束後若 total < 0 回傳 -1，否則回傳最後保留的起點。
// One linear pass tracks `total` (full-loop balance) and `tank` (current
// segment balance). Whenever `tank` goes negative, no station in the current
// segment can be a valid start, so we move start to i+1 and reset tank.

int canCompleteCircuit(int* gas, int gasSize, int* cost, int costSize) {
    // gasSize 與 costSize 題目保證相等，這裡用 gasSize 即可。
    // gasSize == costSize is guaranteed; we only need one of them as n.
    int n = gasSize;

    int total = 0;   // 全程 gas[i]-cost[i] 的總和 / running sum over the entire loop
    int tank  = 0;   // 目前候選段的累計油量 / running tank for the current candidate segment
    int start = 0;   // 目前候選的起始站索引 / index of the current candidate start station

    // 走訪每一個加油站一次 / visit every station exactly once
    for (int i = 0; i < n; i++) {
        // 這一站淨增加的油量；可能為負（cost 大於 gas）/
        // net gas change at station i; can be negative when cost > gas
        int diff = gas[i] - cost[i];

        total += diff;   // 加進整圈總和 / accumulate into the full-loop balance
        tank  += diff;   // 加進此段的油量 / accumulate into this segment's tank

        // 若油量變負，說明從 start 到 i 中的任一站都不能當起點 /
        // If tank went negative, no station from `start` to `i` can be a valid start.
        if (tank < 0) {
            start = i + 1;  // 下一個可能起點是 i+1 / next candidate start is i+1
            tank  = 0;      // 重置此段的累計 / reset segment tank to 0
        }
    }

    // total >= 0 才存在合法起點；否則整圈油不夠用 /
    // A valid start exists iff total >= 0; otherwise the loop is infeasible.
    // 三元運算子 ? : 等同於 if-else 的精簡寫法 /
    // The ternary `cond ? a : b` is shorthand for an if-else expression.
    return total >= 0 ? start : -1;
}
