// 演算法 / Algorithm:
// 同 C 版本：單次線性掃描，total 判斷可行性，tank 變負就重設起點。
// 若 total < 0 回傳 -1，否則回傳最後留下的 start。
// Same as the C version: a single linear pass, where `total` decides
// feasibility and `tank` going negative triggers a start reset.

class Solution {
public:
    // vector<int> 是 STL 的動態陣列；用 const& 傳入避免複製 /
    // vector<int> is the STL dynamic array; pass by const& to avoid copying.
    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
        // .size() 回傳的是 size_t（無號），轉成 int 比較直觀且避免無號比較陷阱 /
        // .size() returns size_t (unsigned); cast to int for clearer signed loops.
        int n = static_cast<int>(gas.size());

        int total = 0;   // 全程淨油量總和 / full-loop net balance
        int tank  = 0;   // 目前候選段的累計 / current segment's tank
        int start = 0;   // 目前候選起點 / current candidate start

        // 範圍式 for 也可，但用索引版本更貼近題意（需要記 i+1 當下一起點）/
        // A range-for would work, but indexed loop fits naturally since we need i+1 on reset.
        for (int i = 0; i < n; ++i) {
            int diff = gas[i] - cost[i];   // 此站淨增油量 / net change at station i
            total += diff;                 // 累計入整圈總和 / add to full-loop sum
            tank  += diff;                 // 累計入目前段 / add to current segment

            // 油量轉負 → 跳過 [start..i]，從 i+1 重啟 /
            // tank dipped below zero → skip [start..i], restart at i+1
            if (tank < 0) {
                start = i + 1;
                tank  = 0;
            }
        }

        // C++ 同 C：用三元運算子簡潔表達 / ternary picks the answer concisely
        return total >= 0 ? start : -1;
    }
};
