1 min readMay 22, 2021

--

## Given an array of positive numbers, where each element represents the max number of jumps that can be made forward from that element, write a program to find the minimum number of jumps needed to reach the end of the array (starting from the first element). If an element is 0, then we cannot move through that element.

package practice;

public class ArrayJump {

public int countMinJumps(int[] jumps) {

if (jumps == null || jumps.length < 2) {

return 0;

}

int[] minJumps = new int[jumps.length];

minJumps[0] = 0; for (int i = 1; i < minJumps.length; i++) {

minJumps[i] = Integer.MAX_VALUE;

}

for (int i = 1; i < jumps.length; i++) {

for (int start = 0; start < i; start++) {

if ((start + jumps[start]) >= i) {

minJumps[i] = Math.min(minJumps[i], minJumps[start] + 1);

}

}

}

return minJumps[minJumps.length - 1];

}

public static void main(String[] args) {

ArrayJump aj = new ArrayJump();

int[] jumps = {2, 1, 1, 1, 4};

System.out.println(aj.countMinJumps(jumps));

jumps = new int[]{1, 1, 3, 6, 9, 3, 0, 1, 3};

System.out.println(aj.countMinJumps(jumps));

}

}

Reference Video: https://www.youtube.com/watch?v=cETfFsSTGJI