-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjumpGame.py
More file actions
24 lines (24 loc) · 859 Bytes
/
Copy pathjumpGame.py
File metadata and controls
24 lines (24 loc) · 859 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution:
# Initial approach:
# Checks if you can reach the last index starting from the first,
# where each element represents your max jump length at that position
# Too complex
# def canJump(self, nums: List[int]) -> bool:
# n = len(nums)
# path = [False] * n
# path[0] = True
# for i in range(n):
# if path[i]:
# max_jump = n if (i + nums[i]) >= n else i + nums[i] + 1
# path[i:max_jump] = ((max_jump - i)) * [True]
# return path[-1]
# Optimized approach: Tracks maximum reachable distance at each step.
def canJump(nums: list[int]) -> bool:
jump = nums[0]
for n in nums:
if jump < 0:
return False
elif n > jump:
jump = n
jump -= 1
return True