Skip to content

Commit 1362317

Browse files
authored
Update readme.md
1 parent 607edf0 commit 1362317

File tree

1 file changed

+35
-1
lines changed
  • src/main/java/g0001_0100/s0045_jump_game_ii

1 file changed

+35
-1
lines changed

src/main/java/g0001_0100/s0045_jump_game_ii/readme.md

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,4 +29,38 @@ Return _the minimum number of jumps to reach index_ `n - 1`. The test cases are
2929

3030
* <code>1 <= nums.length <= 10<sup>4</sup></code>
3131
* `0 <= nums[i] <= 1000`
32-
* It's guaranteed that you can reach `nums[n - 1]`.
32+
* It's guaranteed that you can reach `nums[n - 1]`.
33+
34+
To solve the "Jump Game II" problem in Java with a `Solution` class, we can follow these steps:
35+
36+
1. Define a `Solution` class.
37+
2. Define a method named `jump` that takes an array of non-negative integers `nums` as input and returns the minimum number of jumps required to reach the last index.
38+
3. Initialize variables `maxReach`, `steps`, and `end` to keep track of the maximum reachable position, the number of steps taken, and the end position respectively. Initialize `maxReach` to 0 and `end` to 0.
39+
4. Iterate through the array from index 0 to `nums.length - 2`:
40+
- Update `maxReach` as the maximum of `maxReach` and `i + nums[i]`.
41+
- If the current index `i` equals `end`, update `end` to `maxReach` and increment `steps`.
42+
5. Return `steps`.
43+
44+
Here's the implementation:
45+
46+
```java
47+
public class Solution {
48+
public int jump(int[] nums) {
49+
int maxReach = 0;
50+
int steps = 0;
51+
int end = 0;
52+
53+
for (int i = 0; i < nums.length - 1; i++) {
54+
maxReach = Math.max(maxReach, i + nums[i]);
55+
if (i == end) {
56+
end = maxReach;
57+
steps++;
58+
}
59+
}
60+
61+
return steps;
62+
}
63+
}
64+
```
65+
66+
This implementation provides a solution to the "Jump Game II" problem in Java. It calculates the minimum number of jumps required to reach the last index by iterating through the array and updating the maximum reachable position and the end position accordingly.

0 commit comments

Comments
 (0)