/*
 * 演算法 / Algorithm:
 *   雙指針從兩端往中間掃描，每步計算當前面積並更新最大值，
 *   然後移動較矮的那一邊（移動較高的一邊絕不可能變大）。
 *   Two pointers from both ends; each step compute area, update max,
 *   then move the shorter side (moving the taller side can never help).
 *   Time O(n), Space O(1).
 */

int maxArea(int* height, int heightSize) {
    int left = 0;                                  // 左指針從 0 開始 / left pointer starts at 0
    int right = heightSize - 1;                    // 右指針從最後一格 / right pointer at last index
    int best = 0;                                  // 紀錄目前最大面積 / track the best area so far

    while (left < right) {                         // 當兩指針未相遇就繼續 / loop until pointers meet
        int h_left = height[left];                 // 讀取左邊高度 / read left height (array indexing)
        int h_right = height[right];               // 讀取右邊高度 / read right height
        int minH = h_left < h_right ? h_left : h_right;  // 較矮的牆決定水位 / shorter wall caps the water
        int width = right - left;                  // 兩線間的距離 = 寬 / horizontal distance = width
        int area = minH * width;                   // 矩形面積 / rectangle area

        if (area > best) {                         // 比已知最大還大就更新 / update if better
            best = area;                           // 更新最佳值 / save new best
        }

        if (h_left < h_right) {                    // 左邊較矮 / left side is the limiting one
            left++;                                // 把左指針往右移一格 / advance left inward
        } else {                                   // 右邊較矮或同高 / right is shorter or equal
            right--;                               // 把右指針往左移一格 / advance right inward
        }
        // 註：相等時移動哪邊都一樣 — 兩種情況下，剩下的另一邊都不可能配出更大面積。
        // Note: on ties either side works — neither pairing with the other end can beat current area.
    }

    return best;                                   // 回傳答案 / return the max area
}
