// 演算法：貪心一次掃描。維護 maxReach = 目前能到的最遠 index；
// 若某一格 i > maxReach 表示走不到，回傳 false；若 maxReach 涵蓋終點，回傳 true。
// Algorithm: a single greedy sweep. Track maxReach = farthest reachable index so far.
// If we ever hit i > maxReach the end is unreachable; if maxReach covers n-1 we win.

#include <stdbool.h>  // 引入 bool 型別 / brings in the bool type for C

bool canJump(int* nums, int numsSize) {
    // numsSize 是 nums 陣列的元素個數；LeetCode 的 C 介面會把長度單獨傳進來
    // numsSize is the array length; LeetCode's C signature passes it separately
    int maxReach = 0;  // 目前能到的最遠 index，初始就是起點 0 / farthest reachable index, starts at 0

    for (int i = 0; i < numsSize; i++) {  // 由左到右遍歷每一格 / sweep left-to-right
        if (i > maxReach) {  // 這格根本走不到 → 後面也走不到 / cell i is unreachable, so is the end
            return false;    // 提早結束，回傳失敗 / short-circuit: return false
        }

        int jumpEnd = i + nums[i];  // 從 i 出發最遠能踏到的 index / farthest landing spot from i
        if (jumpEnd > maxReach) {   // 比現有紀錄更遠才更新 / only update if it's an improvement
            maxReach = jumpEnd;     // 更新最遠可達 / record the new best
        }

        if (maxReach >= numsSize - 1) {  // 已經能蓋到終點 / we already cover the last index
            return true;                 // 提早回傳成功 / early exit with success
        }
    }

    // 走完整個迴圈仍沒提早返回，理論上不會發生（n>=1 時 i=n-1 就會觸發上面的 true）
    // If the loop ends without returning, all cells were reachable — return true defensively.
    return true;
}
