Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 31669c2

Browse files
committed
feat: add solution for jump game in python
1 parent 1d02a87 commit 31669c2

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

‎alternative/medium/jump_game.py‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
from typing import List
2+
3+
def canJump(nums: List[int]) -> bool:
4+
goal = len(nums) - 1
5+
6+
for i in range(len(nums) - 1, -1, -1):
7+
if i + nums[i] >= goal:
8+
goal = i
9+
10+
return True if goal == 0 else False
11+
12+
"""
13+
Algorithm 1: Greedy
14+
- Start from the end of the array
15+
- Keep track of the goal
16+
- If the current index + the value at the current index is greater than
17+
or equal to the goal, update the goal to the current index
18+
- If the goal is 0, return True
19+
- Else, return False
20+
- O(n) time complexity
21+
- O(1) space complexity
22+
23+
"""
24+
25+
assert canJump([2, 3, 1, 1, 4]) == True
26+
assert canJump([3, 2, 1, 0, 4]) == False
27+
assert canJump([0]) == True
28+
assert canJump([1, 0, 1, 0]) == False
29+
assert canJump([1, 1, 1, 0]) == True

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /