Minimum Jumps – Dynamic Programming

Given an array of integers where each element represents the max number of steps that can be made forward from that element. Print the minimum number of jumps to reach the end of the array (starting from the first element). If an element is 0, then cannot move through that element.

Input Format

n, size of array Ai, array elements

Output Format

Number of minimum jumps

Sample Input

11
1 3 5 8 9 2 6 7 6 8 9

Sample Output

3

Explanation

3 (1-> 3 -> 8 ->9)

Solution – Java Program

import java.util.*;
public class Main {
    public static void main(String args[]) {
		Scanner scan = new Scanner(System.in);
		int n = scan.nextInt();
		int[] arr = new int[n];
		for(int i=0;i<n;i++)
		{
			arr[i] = scan.nextInt();
		}
		int[] dp = new int[n+1];
		dp[0] = 0;
		for(int i=1;i<=n;i++)
		{
			dp[i] = Integer.MAX_VALUE;
			for(int j=0;j<i;j++)
			{
				if(i-j <= arr[j] && dp[j] != Integer.MAX_VALUE)
				{
					dp[i] = Math.min(dp[i],1+dp[j]);
				}
			}
		}
		System.out.println(dp[n]);
    }
}

Leave a Comment

Your email address will not be published. Required fields are marked *