Jump Game II in Python

class Solution:
    def jump(self, nums: List[int]) -> int:
        """
        Function to find the minimum number of jumps to reach the last index.

        The function uses a greedy algorithm approach where it iteratively identifies the farthest it
        can reach from the current position and makes a jump to the position that gives the maximum
        reach.

        Args:
        nums (List[int]): List of non-negative integers representing the maximum jump length at each position.

        Returns:
        int: The minimum number of jumps needed to reach the last index.
        """
        jumps = 0  # Number of jumps needed
        current_jump_end = 0  # End of the range that we can jump to
        farthest = 0  # Farthest point that we can reach

        # We don't need to consider the last element in nums, as we can't jump from there
        for i in range(len(nums) - 1):
            # Update the farthest point we can reach
            farthest = max(farthest, i + nums[i])

            # If we've reached the end of the current jump,
            # increase the jump count and set new current jump end to farthest
            if i == current_jump_end:
                jumps += 1
                current_jump_end = farthest

        return jumps

PrevNext