The problem is get the minimum jumps
and the corresponding indices in the array that lead to end of array
with lesser jumps. for ex:
{3,2,3,1,5,4}
would take 2 jump
s.
Jump 1 from index 0 to index 2
jump 2 from index 2 to index 5
By Jump, I mean hopping; i.e how many hops are needed. if you are a particular index, you get to hop by the value in that index.
Here is my implementation in Java
, which gives the minimum number of jumps correctly, but I am having difficulty updating the list
that I have with indices
corresponding to the hop positions. how can I get it to working?
public static int minJumps2(int[] arr, List<Integer> jumps){
int minsteps=0;
boolean reachedEnd=false;
if (arr.length<2)
return 0;
int farthest=0;
for (int i=0;i<=farthest;i++){
farthest=Math.max(farthest, arr[i]+i);
if (farthest>=arr.length-1){
jumps.add(i);
reachedEnd=true;
break;
}
//jumps.add(farthest);
minsteps++;
}
if (!reachedEnd){
System.out.println("unreachable");
return -1;
}
System.out.println(minsteps);
System.out.println(jumps);
return minsteps;
}
public static void main(String[] args){
int[] arr= {3,2,3,1,5};
List<Integer> jumps=new ArrayList<Integer>();
minJumps2(arr,jumps);
}
I am using the Jump game algorithm as described here: Interview puzzle: Jump Game