#45
Medium Algorithms Jump game ii
Array Dynamic Programming Greedy
42.5% acceptance
Jan 12, 2026
16384
702
You are given a 0-indexed array of integers nums of length n. You are initially positioned at index 0.
Each element nums[i] represents the maximum length of a forward jump from index i. In other words, if you are at index i, you can jump to any index (i + j) where:
0 <= j <= nums[i] and
i + j < n
Return the minimum number of jumps to reach index n - 1. The test cases are generated such that you can reach index n - 1.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn jump(nums: Vec<i32>) -> i32 {
let n = nums.len();
if n <= 1 {
return 0;
}
let mut jumps = 0;
let mut current_end = 0;
let mut farthest = 0;
for i in 0..n - 1 {
farthest = farthest.max(i + nums[i] as usize);
if i == current_end {
jumps += 1;
current_end = farthest;
if current_end >= n - 1 {
break;
}
}
}
jumps
}
}