Skip to content

Commit 8392c82

Browse files
leetcode 45
1 parent 535a799 commit 8392c82

1 file changed

Lines changed: 31 additions & 0 deletions

File tree

Leetcode/Leetcode_45.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
from typing import List
2+
3+
class Solution:
4+
def jump(self, nums: List[int]) -> int:
5+
"""
6+
LeetCode 45 - Jump Game II
7+
8+
Goal:
9+
Find the minimum number of jumps required to reach the last index.
10+
11+
Approach:
12+
Greedy (Range-based traversal)
13+
"""
14+
15+
count = 0 # Number of jumps taken
16+
m = 0 # Farthest index we can reach so far
17+
curr = 0 # End of current jump range
18+
19+
# Traverse till second last index (no need to jump from last index)
20+
for i in range(len(nums) - 1):
21+
22+
# Update the farthest reachable index
23+
# i + nums[i] = maximum distance we can reach from current index
24+
m = max(m, nums[i] + i)
25+
26+
# If we reach the end of current range
27+
if i == curr:
28+
count += 1 # Take a jump
29+
curr = m # Update range to farthest reachable
30+
31+
return count

0 commit comments

Comments
 (0)