Given an array of integers where each element represents the max number
of steps that can be made forward from that element. Write a function to
return the minimum number of jumps to reach the end of the array
(starting from the first element).
E.g.
Input : {2,3,1,1,4}
Output: 2
We can solve this problem in multiple approaches. Here i am going to provide solution in greedy and dynamic programming model.
In greedy approach we find the maximum value to maximize the jump. In dynamic programming approach we compute the minimum number of hops required to reach each element and use these values for computing the result.
Below is the Java implementation of both approaches.
public class FindMinimumHops {
public static void main(String args[])
{
int [] array = {2,3,1,1,4};
System.out.println("Minimum number of hops to reach end is:"+findMinHopsUsingGreedy(array));
System.out.println("Minimum number of hops to reach end is:"+findMinHopsUsingDP(array));
}
private static int findMinHopsUsingGreedy(int[] array) {
int maxHops = 0;
int currentIndex = 0;
int max = 0;
int location = 0;
while (currentIndex < array.length) {
maxHops++;
max = 0;
for (int ctr = currentIndex + 1; ctr <= currentIndex
+ array[currentIndex]; ctr++) {
if (max < array[ctr]) {
max = array[ctr];
location = ctr;
}
}
currentIndex += location;
}
return maxHops;
}
private static int findMinHopsUsingDP(int[] array) {
int []dp = new int[array.length];
dp[0] = 0;
for(int i = 1; i < array.length; i++)
{
dp[i] = Integer.MAX_VALUE;
for(int j= 0; j < i ; j++ )
if( ( i-j ) <= array[j] )
dp[i] = Math.min(dp[i], dp[j]+1);
}
return dp[array.length - 1];
}
}