55. Jump Game
You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position
Example 1:
- Input:
nums = [2,3,1,1,4] - Output:
true - Explanation: Jump
1step from index0to1, then3steps to the last index.
Example 2:
- Input:
nums = [3,2,1,0,4] - Output:
false - Explanation: You will always arrive at index
3no matter what. Its maximum jump length is0, which makes it impossible to reach the last index.
Constraints:
1 <= nums.length <= 10^40 <= nums[i] <= 10^5
Solution
class Solution:
def canJump(self, nums: list[int]) -> bool:
best, last = nums[0], len(nums) - 1
for i in range(last):
if i > best:
return False
else:
pos = nums[i] + i
best = max(best, pos)
return best >= last