#1340
Hard Algorithms Jump game v
Array Dynamic Programming Sorting
64.8% acceptance
Feb 25, 2026
1187
46
Given an array of integers arr and an integer d. In one step you can jump from index i to index:
i + x where: i + x < arr.length and 0 < x <= d.
i - x where: i - x >= 0 and 0 < x <= d.
In addition, you can only jump from index i to index j if arr[i] > arr[j] and arr[i] > arr[k] for all indices k between i and j (More formally min(i, j) < k < max(i, j)).
You can choose any index of the array and start jumping. Return the maximum number of indices you can visit.
Notice that you can not jump outside of the array at any time.
Solution
Rust
Time O(n)
Space O(n)
impl Solution {
pub fn max_jumps(arr: Vec<i32>, d: i32) -> i32 {
let n = arr.len();
let d = d as usize;
let mut dp = vec![0i32; n];
fn dfs(i: usize, arr: &[i32], d: usize, dp: &mut Vec<i32>) -> i32 {
if dp[i] > 0 { return dp[i]; }
let n = arr.len();
let mut best = 1;
// Jump right
for j in 1..=d {
if i + j >= n || arr[i + j] >= arr[i] { break; }
best = best.max(1 + dfs(i + j, arr, d, dp));
}
// Jump left
for j in 1..=d {
if j > i || arr[i - j] >= arr[i] { break; }
best = best.max(1 + dfs(i - j, arr, d, dp));
}
dp[i] = best;
best
}
(0..n).map(|i| dfs(i, &arr, d, &mut dp)).max().unwrap_or(0)
}
}