Code Explanation:
Function Definition
def can_jump(nums):
Defines a function named can_jump that takes a list nums.
Initialize Reach
reach = 0
reach keeps track of the farthest index you can currently jump to.
Initially, you're at index 0, so the reach is 0.
Loop Over Elements with Index
for i, n in enumerate(nums):
Loops through the array while getting both the index i and the value n at each index.
i is your current position.
n is how far you can jump from this position.
Check If Current Position is Reachable
if i > reach:
return False
If you're standing on an index that's greater than the farthest you've been able to reach, you can't proceed—so return False.
Update Maximum Reach
reach = max(reach, i + n)
From the current position i, the farthest you can go is i + n.
Update reach to the maximum of the current reach and i + n.
If Loop Finishes, You Can Reach the End
return True
If you never hit a point that is unreachable, return True.
Final reach is 8, which is beyond the last index (4).
Output:
True
.png)

0 Comments:
Post a Comment