// 演算法 / Algorithm:
// 與 C 版相同的貪婪解法，O(n) 時間 O(1) 空間。
// Same greedy O(n)-time, O(1)-space algorithm as the C version.

#include <vector>      // 提供 std::vector / provides std::vector
#include <algorithm>   // 提供 std::max / provides std::max

class Solution {
public:
    // vector<int>& 是「對 vector<int> 的引用」，避免複製整個陣列。
    // vector<int>& is a reference to a vector — passes by reference, no copy.
    int jump(std::vector<int>& nums) {
        int n = static_cast<int>(nums.size());  // 取陣列長度，轉成 int / get size as int
        int jumps = 0;        // 已跳次數 / jump count
        int currentEnd = 0;   // 目前這跳的右邊界 / current jump's right boundary
        int farthest = 0;     // 下一跳能到的最遠處 / farthest reachable in one more jump

        // 只掃到 n-2，避免在 i = n-1 時多算一次跳躍。
        // Iterate only up to n-2 to avoid over-counting at the last index.
        for (int i = 0; i < n - 1; ++i) {
            // std::max 取兩數中較大者 / std::max returns the greater of two values
            farthest = std::max(farthest, i + nums[i]);

            // 抵達邊界時，必須再消耗一次跳躍。
            // When i reaches currentEnd, we must spend one more jump.
            if (i == currentEnd) {
                ++jumps;                   // 前綴遞增，比 jumps++ 略快但結果相同
                                           // pre-increment, semantically same as jumps++
                currentEnd = farthest;     // 進入下一層 / move to next layer

                // 提前結束：已能涵蓋終點 / early exit: end is reachable
                if (currentEnd >= n - 1) break;
            }
        }

        return jumps;  // 回傳答案 / return the answer
    }
};
