// 演算法：邊走訪 gain 邊累加成「目前海拔」cur，並用 best 記錄最高海拔。
// Algorithm: scan gain while accumulating into cur (the current altitude),
// and keep best as the highest altitude ever seen. O(n) time, O(1) space.

int largestAltitude(int* gain, int gainSize) {
    // cur 是目前所在點的海拔，從起點 0 開始。
    // cur is the altitude of the current point, starting at 0 (the start point).
    int cur = 0;

    // best 是目前見過的最高海拔，也從 0 開始（因為起點海拔就是 0）。
    // best is the highest altitude so far, also starting at 0 (the start is altitude 0).
    int best = 0;

    // 逐一走訪 gain 的每個元素；i 是陣列索引，從 0 到 gainSize-1。
    // Loop over each element of gain; i is the array index, from 0 to gainSize-1.
    for (int i = 0; i < gainSize; i++) {
        // gain[i] 是陣列第 i 個值，用方括號取值；把它加到 cur 上得到下一個點的海拔。
        // gain[i] reads the i-th value (bracket indexing); add it to cur to get the next altitude.
        cur += gain[i];

        // 如果新的海拔 cur 比目前的最高紀錄還高，就更新 best。
        // If the new altitude cur beats the current record, update best.
        if (cur > best) {
            best = cur;
        }
    }

    // 走完整條路後，best 就是最高海拔，回傳它。
    // After the whole trip, best holds the highest altitude; return it.
    return best;
}
