// 演算法：暴力枚舉每一對 (陸上, 水上)，兩種順序都試，回傳最小結束時間。
// Algorithm: brute-force every (land, water) pair, try both orders, return the min finish.
// n,m <= 100, so at most 20000 cases — trivially fast.

class Solution {
public:
    int earliestFinishTime(vector<int>& landStartTime, vector<int>& landDuration,
                           vector<int>& waterStartTime, vector<int>& waterDuration) {
        int ans = INT_MAX;  // INT_MAX 是 int 能表示的最大值，當作初始上界 / largest int, used as initial upper bound

        // range-for 之外用傳統索引，因為要同時取 start 與 duration 兩個陣列的同一格
        // use index loops because we need the same index into both the start and duration arrays
        for (size_t i = 0; i < landStartTime.size(); ++i) {
            for (size_t j = 0; j < waterStartTime.size(); ++j) {

                // 先陸後水 / land first
                int landFinish = landStartTime[i] + landDuration[i];
                // std::max 回傳較大值：確保水上設施不早於開放時間開始 / max enforces the opening time
                int plan1 = max(landFinish, waterStartTime[j]) + waterDuration[j];

                // 先水後陸 / water first
                int waterFinish = waterStartTime[j] + waterDuration[j];
                int plan2 = max(waterFinish, landStartTime[i]) + landDuration[i];

                // 這一對取較早的順序，再更新全域最小值 / take the earlier order, then update the global min
                ans = min(ans, min(plan1, plan2));
            }
        }
        return ans;  // 最早完成時間 / earliest finish time
    }
};
