Tech for good

[Leetcode/Greedy] 55. Jump Game 본문

IT/Computer Science

[Leetcode/Greedy] 55. Jump Game

Diana Kang 2025. 6. 9. 22:41

https://leetcode.com/problems/jump-game/description/

class Solution:
    def canJump(self, nums: List[int]) -> bool:
        max_reach = 0
        for i in range(len(nums)):
            if i > max_reach:
                return False  # Current index is unreachable
            max_reach = max(max_reach, i + nums[i])  # Update the farthest reachable index
        return True

✅ Explanation:

  • max_reach keeps track of the furthest index you can reach at any point.
  • For every index i:
    • If i > max_reach, it means you’re stuck and can’t move forward — return False.
    • Otherwise, update max_reach as the furthest you can go from the current position.
  • If the loop completes, it means all indices are reachable — return True.