Skip to content

Commit 97ffdd3

Browse files
committed
adding new algo
1 parent c0a4d88 commit 97ffdd3

File tree

1 file changed

+31
-0
lines changed
  • src/my_project/interviews/amazon_high_frequency_23/round_2

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
class Solution:
2+
def jump(self, nums: List[int]) -> int:
3+
"""
4+
Greedy approach: At each position, jump to the farthest reachable index
5+
6+
Example: [2,3,1,1,4]
7+
- From index 0 (value=2): can reach indices 1,2
8+
- Greedy choice: Jump to index 1 (value=3) because it reaches farthest
9+
- From index 1: can reach indices 2,3,4 (end)
10+
- Answer: 2 jumps
11+
"""
12+
13+
if len(nums) <= 1:
14+
return 0
15+
16+
jumps = 0
17+
current_end = 0 # End of current jump range
18+
farthest = 0 # The farthest position we can reach
19+
20+
for i in range(len(nums) - 1):
21+
# Update farthest position reachable
22+
farthest = max(farthest, i + nums[i])
23+
24+
# If we've reached the end of current jump range
25+
if i == current_end:
26+
jumps += 1
27+
current_end = farthest # Make the greedy choice
28+
29+
if current_end > len(nums) - 1:
30+
break
31+
return jumps

0 commit comments

Comments
 (0)