// Algorithm / 演算法：
// 與 C 版本完全相同：按 (minimum - actual) 由大到小排序後掃描，
// 取 max(spent + minimum) 作為答案。這裡用 std::sort + lambda 表達。
// Same idea as the C version: sort by (min - actual) descending and sweep,
// taking the max of (spent + minimum). Implemented with std::sort + a lambda.

#include <vector>
#include <algorithm>   // std::sort, std::max

class Solution {
public:
    int minimumEffort(std::vector<std::vector<int>>& tasks) {
        // std::sort + lambda 比較函式
        // a, b 都是 const vector<int>& （tasks 的一列）
        // The lambda is a comparator: return true when a should come before b.
        // 我們要 slack 大的在前 / we want larger slack first.
        std::sort(tasks.begin(), tasks.end(),
                  [](const std::vector<int>& a, const std::vector<int>& b) {
                      // a[1]-a[0] 是 a 的 slack；b[1]-b[0] 是 b 的 slack
                      // Return true ⇒ a comes before b.
                      return (a[1] - a[0]) > (b[1] - b[0]);
                  });

        long spent = 0;   // 已花費的 actual 累計 / running total of actual costs
        long ans   = 0;   // 答案下界 / current best lower bound on initial energy

        // range-for：逐一取得每個任務的 reference (auto& 避免複製)
        // range-for loop: iterate by reference to avoid copying each vector.
        for (const auto& t : tasks) {
            int actual  = t[0];                 // 本任務實際花費 / actual spend
            int minimum = t[1];                 // 本任務開始門檻 / minimum to start
            ans = std::max(ans, spent + minimum); // 更新答案 / tighten lower bound
            spent += actual;                    // 累加花費 / accumulate after finishing
        }
        return static_cast<int>(ans);   // 轉回 int 回傳 / cast back to int
    }
};
