// 演算法：暴力枚舉每一對 (陸上 i, 水上 j)，兩種順序都算，取最早結束時間。
// Algorithm: brute-force every (land i, water j) pair, try both orders,
// and keep the earliest finish time. n*m pairs is tiny, so this is fast enough.

// LeetCode 會把陣列和它們的長度一起傳進來 / LeetCode passes each array with its length.
int earliestFinishTime(int* landStartTime, int landStartTimeSize,
                       int* landDuration, int landDurationSize,
                       int* waterStartTime, int waterStartTimeSize,
                       int* waterDuration, int waterDurationSize) {
    int ans = 2147483647;  // 先設成 int 最大值，之後不斷取較小 / start at INT_MAX, then keep shrinking

    // 外層跑每一個陸上設施 / outer loop over every land ride
    for (int i = 0; i < landStartTimeSize; i++) {
        // 內層跑每一個水上設施 / inner loop over every water ride
        for (int j = 0; j < waterStartTimeSize; j++) {

            // 先陸後水：陸上設施的結束時間 / land first: when the land ride finishes
            int landFinish = landStartTime[i] + landDuration[i];
            // 水上設施不能比開放時間早開始，所以取兩者較大的 / water can't start before it opens
            int startWater = landFinish > waterStartTime[j] ? landFinish : waterStartTime[j];
            int plan1 = startWater + waterDuration[j];  // 加上水上時長 = 整體結束 / add water duration

            // 先水後陸：水上設施的結束時間 / water first: when the water ride finishes
            int waterFinish = waterStartTime[j] + waterDuration[j];
            // 陸上設施同樣不能比它的開放時間早開始 / land likewise can't start before it opens
            int startLand = waterFinish > landStartTime[i] ? waterFinish : landStartTime[i];
            int plan2 = startLand + landDuration[i];    // 加上陸上時長 = 整體結束 / add land duration

            // 這一對的最佳順序 / better of the two orders for this pair
            int best = plan1 < plan2 ? plan1 : plan2;

            // 若比目前答案更早，就更新 / update the global minimum if this is earlier
            if (best < ans) ans = best;
        }
    }
    return ans;  // 全域最早完成時間 / the earliest finish time overall
}
