Jump Game
Examples
Example 1:
Input: nums = [1,2,0,1,0]
Output: true
Explanation:
Example 2:
Input: nums = [1,2,1,0,1]
Output: false
Example 1:
Input: nums = [1,2,0,1,0]
Output: true
Explanation:
Example 2:
Input: nums = [1,2,1,0,1]
Output: false
You are given an integer array nums where each element nums[i] indicates your maximum jump length at that position.
Return true if you can reach the last index starting from index 0, or false otherwise.
First jump from index 0 to 1, then from index 1 to 3, and lastly from index 3 to 4.
1 <= nums.length <= 10000 <= nums[i] <= 1000Greedily track the farthest index reachable so far. As you scan, if the current index exceeds the farthest reach, return false. Otherwise, update the farthest reach with i + nums[i].
If you can reach index i, then you can reach all indices up to the farthest reach computed. If you ever encounter an index beyond that, no sequence of jumps can reach it. If the scan finishes, the last index is reachable.
O(n)O(1)class Solution:
def canJump(self, nums: List[int]) -> bool:
farthest = 0
for i, jump in enumerate(nums):
if i > farthest:
return False
farthest = max(farthest, i + jump)
return True