The Jump Game II problem involves finding the minimum number of jumps required to reach the last index of an array. Each element in the array represents the maximum jump length at that position.
class Solution {
public int jump(int[] nums) {
int jumps = 0, currentEnd = 0, farthest = 0;
for (int i = 0; i < nums.length - 1; i++) {
farthest = Math.max(farthest, i + nums[i]);
if (i == currentEnd) {
jumps++;
currentEnd = farthest;
if (currentEnd >= nums.length - 1) {
break;
}
}
}
return jumps;
}
}
O(N)
, where N
is the length of the array.O(1)
, as no additional space is used.Input: nums = [2, 3, 1, 1, 4]
Output: 2
Explanation:
- Jump 1 step from index 0 to index 1.
- Then jump 3 steps to the last index.