Jump Game II in TypeScript

function jump(nums: number[]): number {
    let jumps: number = 0; // Number of jumps needed
    let currentJumpEnd: number = 0; // End of the range that we can reach with current number of jumps
    let farthest: number = 0; // Farthest point that we can reach

    // Iterate over the array except for the last element
    for (let i = 0; i < nums.length - 1; i++) {
        // Update the farthest point we can reach
        farthest = Math.max(farthest, i + nums[i]);

        // If we've reached the end of the current jump,
        // increase the jump count and update the current jump end
        if (i === currentJumpEnd) {
            jumps++;
            currentJumpEnd = farthest;
        }
    }

    return jumps;
}

PrevNext