// Algorithm: sort nums; a good array becomes [1, 2, ..., n-1, n, n] after sorting.
// 演算法：排序後，好的陣列會是 [1, 2, ..., n-1, n, n]。
// We check nums[i] == i+1 for all i except the last, which must equal n (= length - 1).
// 檢查除最後一格外 nums[i] == i+1，最後一格應等於 n (= 長度 - 1)。

// Comparator for qsort: returns negative/zero/positive so qsort can order ints ascending.
// qsort 用的比較函式：回傳負/零/正，讓 qsort 由小到大排序整數。
int cmp(const void *a, const void *b) {
    // *(int*)a 取出 a 指向的整數 / dereference void pointer as int
    int x = *(const int *)a;
    int y = *(const int *)b;
    // 回傳 x - y 達成升序 / returning x - y gives ascending order
    // 因為 nums[i] <= 200，x - y 不會溢位 / since values <= 200, no overflow
    return x - y;
}

bool isGood(int* nums, int numsSize) {
    // qsort 原地排序 nums / qsort sorts nums in place
    // 參數：陣列、元素個數、每個元素大小 (bytes)、比較函式
    // args: array, element count, element size in bytes, comparator
    qsort(nums, numsSize, sizeof(int), cmp);

    // 預期的 n = 長度 - 1，因為 base[n] 長度為 n + 1
    // expected n = length - 1, because base[n] has n + 1 elements
    int n = numsSize - 1;

    // 邊界：若 n == 0，長度為 1，這不可能是任何 base[n] (base[1] 長度 2)
    // edge case: n == 0 means length 1, which can't match any base[n] (base[1] has length 2)
    if (n < 1) return false;

    // 檢查前 numsSize - 1 個位置：sorted nums[i] 應等於 i + 1
    // check the first numsSize - 1 slots: sorted nums[i] should equal i + 1
    for (int i = 0; i < numsSize - 1; i++) {
        // 若不吻合，直接回傳 false / mismatch → not a good array
        if (nums[i] != i + 1) return false;
    }

    // 最後一格應等於 n (因為 n 出現兩次：在倒數第二與最後一格)
    // last slot should equal n (n appears twice: at positions n-1 and n)
    // 等價地，nums[numsSize - 1] 應等於 numsSize - 1
    // equivalently, nums[last] should equal numsSize - 1
    if (nums[numsSize - 1] != n) return false;

    // 全部通過 / all checks passed
    return true;
}
