Skip to content

Commit

Permalink
feat: [Week 10-4] solve jump game
Browse files Browse the repository at this point in the history
  • Loading branch information
Chaedie committed Feb 14, 2025
1 parent e5e8060 commit 62eaa5c
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions jump-game/Chaedie.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
class Solution:
"""
Solution 1:
λ’€μ—μ„œ λΆ€ν„° ν‘ΈλŠ” 방법이 μžˆμ„κ±°λΌ μƒκ°ν–ˆμŠ΅λ‹ˆλ‹€.
ν’€μ΄λŠ” μ„±κ³΅ν–ˆμ§€λ§Œ μ„±λŠ₯은 느린 5% λΌλŠ” 느린 μ„±λŠ₯을 λ³΄μž…λ‹ˆλ‹€.
Time: O(n * 10^5) - 10^5 λŠ” nums μ›μ†Œμ˜ μ΅œλŒ€ κ°’
Space: O(n)
"""

def canJump(self, nums: List[int]) -> bool:
dp = [False for i in range(len(nums))]

dp[len(nums) - 1] = True

for i in range(len(nums) - 1 - 1, -1, -1):
for j in range(1, nums[i] + 1):
if i + j < len(nums) and dp[i + j]:
dp[i] = True
break

return dp[0]

"""
Solution 2:
Greedy - μ†”λ£¨μ…˜μ„ μ°Έκ³ ν–ˆμŠ΅λ‹ˆλ‹€.
Time: O(n)
Space: O(1)
"""

def canJump(self, nums: List[int]) -> bool:
reach = 0
for idx in range(len(nums)):
if idx <= reach:
reach = max(reach, idx + nums[idx])
return reach >= len(nums) - 1

0 comments on commit 62eaa5c

Please sign in to comment.