Array Hopper III
public class Solution {
public int minJump(int[] array) {
// let N be length of input array
int n = array.length;
// create N length memoization array
int[] m = new int[n];
// walk backwards
for (int i = n - 1; i >= 0; i--) {
int maxJumps = array[i];
// base case
if (maxJumps + i >= m.length) {
m[i] = 1;
continue;
}
// inductive step
int bestJump = Integer.MAX_VALUE;
for (int j = i; j <= i + maxJumps; j++) {
if (m[j] > 0) {
// found a path to the end
bestJump = Math.min(bestJump, m[j] + 1);
}
}
// if we found a path to the end, update accordingly
if (bestJump != Integer.MAX_VALUE) {
m[i] = bestJump;
}
}
return m[0] == 0 ? -1 : m[0];
}
}
Last updated