Skip to content

Commit c522936

Browse files
committed
O(n) time and O(1) space using Greedy Approach.
1 parent 29134ab commit c522936

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

55. Jump Game/55. Jump Game.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
"""
2+
Given an array of non-negative integers, you are initially positioned at the first index of the array.
3+
4+
Each element in the array represents your maximum jump length at that position.
5+
6+
Determine if you are able to reach the last index.
7+
8+
Example 1:
9+
10+
Input: [2,3,1,1,4]
11+
Output: true
12+
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
13+
Example 2:
14+
15+
Input: [3,2,1,0,4]
16+
Output: false
17+
Explanation: You will always arrive at index 3 no matter what. Its maximum
18+
jump length is 0, which makes it impossible to reach the last index.
19+
"""
20+
class Solution:
21+
def canJump(self, nums: List[int]) -> bool:
22+
lastIndex = len(nums) - 1
23+
for i in range(len(nums)-1,-1,-1):
24+
if i + nums[i] >= lastIndex:
25+
lastIndex = i
26+
return lastIndex == 0

0 commit comments

Comments
 (0)