// 演算法 / Algorithm:
// 1) 從左到右找「最長連續前綴」，同時累加它的總和 s。
//    Walk left-to-right to find the longest sequential prefix and sum it into s.
// 2) 用一個布林陣列標記所有出現過的值，再從 s 往上找第一個沒出現的數。
//    Mark every value seen in a boolean array, then scan up from s for the first missing one.

int missingInteger(int* nums, int numsSize) {
    // s 先設成第一個元素，因為長度至少為 1，單元素前綴一定連續。
    // Start s at the first element; length >= 1, so a single-element prefix is always sequential.
    int s = nums[0];

    // 從下標 1 開始檢查是否能繼續延伸連續前綴。
    // From index 1, check whether the sequential run can keep extending.
    for (int i = 1; i < numsSize; i++) {
        // 只有當這個數剛好是前一個數 +1 時，前綴才連續。
        // The prefix stays sequential only if this value is exactly previous + 1.
        if (nums[i] == nums[i - 1] + 1) {
            s += nums[i];   // 把這個元素加進總和 / add this element to the sum
        } else {
            break;          // 一旦斷裂就停止，前綴到此為止 / break: the prefix ends here
        }
    }

    // seen[v] = 1 代表值 v 在 nums 裡出現過。值域 1..50，開 51 大小即可安全索引。
    // seen[v] = 1 means value v appears in nums. Values are 1..50, so size 51 covers all indices.
    int seen[51] = {0};   // 全部初始化為 0（都沒出現） / initialise all to 0 (nothing seen yet)

    // 把每個元素標記成「出現過」。
    // Mark each element as "present".
    for (int i = 0; i < numsSize; i++) {
        seen[nums[i]] = 1;   // 用值當索引直接打標記 / use the value itself as the index
    }

    // 從 s 開始往上找第一個沒被標記的整數。
    // Starting at s, find the first integer that is not marked as seen.
    int x = s;
    // 條件：x 在 1..50 範圍內 且 已經出現過，就繼續往上找。
    // While x is within 1..50 AND already seen, keep incrementing.
    // 超過 50 的數一定沒在陣列裡（值最大 50），可以直接回傳。
    // Any x above 50 cannot be in the array (max value is 50), so it must be the answer.
    while (x <= 50 && seen[x] == 1) {
        x++;   // 這個數在陣列裡，試下一個 / this value exists, try the next one
    }

    return x;   // 第一個大於等於 s 且缺失的整數 / first integer >= s that is missing
}
