0055. Jump Game
Medium | Greedy + DP | 460 ms (91.12%), 15.2 MB (91.02%)
Input: nums = [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
Input: nums = [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.class Solution:
def canJump(self, nums: List[int]) -> bool:
# (base case)
if len(nums) == 1: return True
if nums[0] == 0: return False
# ==================================================
# Greedy =
# ==================================================
# time : O(n)
# space : O(1)
prevIndex = len(nums) - 1
for i in range(len(nums)-1, -1, -1):
if i + nums[i] >= prevIndex: prevIndex = i
return prevIndex == 0
'''
# ==================================================
# Dynamic Programming =
# ==================================================
# time : O(n)
# space : O(n)
dp = [False] * len(nums)
dp[-1] = True
cur = len(nums) - 1
for i in range(len(nums)-2, -1, -1):
if i + nums[i] >= cur:
dp[i] = True
cur = i
return dp[0] == True
'''Last updated