Skip to content

Commit dfdf9f5

Browse files
committed
https://leetcode.com/problems/jump-game-ii/
1 parent f27a86f commit dfdf9f5

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

MediumProblems/JumpGameII.cs

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
namespace LeetCode.MediumProblems;
2+
3+
/// <summary>
4+
/// https://leetcode.com/problems/jump-game-ii/
5+
/// </summary>
6+
public class JumpGameII
7+
{
8+
public int Jump(int[] nums)
9+
{
10+
int jumps = 0; // Total jumps needed
11+
int currentEnd = 0; // Boundary of current jump range
12+
int farthest = 0; // Maximum reachable index
13+
14+
// Iterate through all positions except last (no jump needed from end)
15+
for (int i = 0; i < nums.Length - 1; i++)
16+
{
17+
// Update maximum reachable index from current position
18+
farthest = Math.Max(farthest, i + nums[i]);
19+
20+
// When reaching current boundary, make jump and update boundary
21+
if (i == currentEnd)
22+
{
23+
jumps++;
24+
currentEnd = farthest; // New reachable range for next jump
25+
}
26+
}
27+
28+
return jumps; // Minimum jumps to reach end
29+
}
30+
}

0 commit comments

Comments
 (0)