// Algorithm / 演算法: same counting-sort bucket as the C version. Cap citations at n,
// bucket them, sweep h from n downward keeping a running count of "papers with ≥ h
// citations", and return the first h with count >= h. O(n) time, O(n) space.

#include <vector>          // std::vector — 動態陣列 / dynamic array container
#include <algorithm>       // std::min — 取最小值 / utility function

class Solution {
public:
    int hIndex(std::vector<int>& citations) {
        int n = static_cast<int>(citations.size());   // n 是論文總數 / total paper count

        // std::vector<int> 預設初始化為 0；長度 n+1 對應 h 可能值 0..n
        // std::vector<int> default-initializes elements to 0; length n+1 covers h = 0..n.
        std::vector<int> bucket(n + 1, 0);

        // range-for 是 C++11 的語法糖：for (auto x : container) 逐一拿出每個元素
        // Range-for is C++11 sugar: iterates each element, here as `int c`.
        for (int c : citations) {
            // std::min(c, n) 把超過 n 的引用數壓回 n，因為 h 不會超過 n
            // std::min(c, n) caps citations at n — h-index can't exceed n anyway.
            bucket[std::min(c, n)]++;                 // 對應桶子 +1 / increment matching bucket
        }

        int count = 0;                                // 累計後綴計數 / running suffix count
        // 從大的 h 開始掃，第一個成立的就是最大的 h
        // Sweep from large h downward; first hit is automatically the maximum.
        for (int h = n; h >= 0; --h) {
            count += bucket[h];                       // 把這一桶加進累計 / add this bucket's papers
            if (count >= h) {                         // 至少 h 篇論文，每篇 ≥ h 次引用 / definition satisfied
                return h;                             // 即是 h-index / this is the answer
            }
        }

        return 0;                                     // 不會執行到，h=0 必成立 / unreachable; h=0 always works
    }
};
