The Wayback Machine - https://web.archive.org/web/20240818163937/https://www.geeksforgeeks.org/minimum-number-of-jumps-to-reach-end-of-a-given-array/
Open In App

Jump Game – Minimum Jumps to Reeach End

Last Updated : 14 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given an array arr[] where each element represents the max number of steps that can be made forward from that index. The task is to find the minimum number of jumps to reach the end of the array starting from index 0.

Examples: 

Input: arr[] = {1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9}
Output: 3 (1-> 3 -> 9 -> 9)
Explanation: Jump from 1st element to 2nd element as there is only 1 step.
Now there are three options 5, 8 or 9. If 8 or 9 is chosen then the end node 9 can be reached. So 3 jumps are made.

Input:  arr[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}
Output: 10
Explanation: In every step a jump is needed so the count of jumps is 10.

Using Recursion: 

Start from the first element and recursively call for all the elements reachable from the first element. The minimum number of jumps to reach end from first can be calculated using the minimum value from the recursive calls. 

minJumps(start, end) = 1 + Min(minJumps(k, end)) for all k reachable from start.

Follow the steps mentioned below to implement the idea:

  • Create a recursive function.
  • In each recursive call get all the reachable nodes from that index.
    • For each of the index call the recursive function.
    • Find the minimum number of jumps to reach the end from current index.
  • Return the minimum number of jumps from the recursive call.

Below is the Implementation of the above approach:

C++
#include <bits/stdc++.h>
using namespace std;

// Function to return the minimum number
// of jumps to reach arr[h] from arr[l]
int minJumps(vector<int>& arr, int l, int h) {

    // Base case: when source and destination are same
    if (h == l)
        return 0;

    // When nothing is reachable from the given source
    if (arr[l] == 0)
        return INT_MAX;

    // Traverse through all the points
    // reachable from arr[l]
    // Recursively, get the minimum number
    // of jumps needed to reach arr[h] from
    // these reachable points
    int min = INT_MAX;
    for (int i = l + 1; i <= h && i <= l + arr[l]; i++) {
        int jumps = minJumps(arr, i, h);
        if (jumps != INT_MAX && jumps + 1 < min)
            min = jumps + 1;
    }

    return min;
}

// Driver Code
int main() {
    vector<int> arr = { 1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9 };
    int n = arr.size();
    cout << "Minimum number of jumps to";
    cout << " reach the end is " << minJumps(arr, 0, n - 1);
    return 0;
}
C
// C program to find Minimum
// number of jumps to reach end
#include <limits.h>
#include <stdio.h>

// Returns minimum number of
// jumps to reach arr[h] from arr[l]
int minJumps(int arr[], int l, int h)
{
    // Base case: when source and destination are same
    if (h == l)
        return 0;

    // When nothing is reachable from the given source
    if (arr[l] == 0)
        return INT_MAX;

    // Traverse through all the points
    // reachable from arr[l]. Recursively
    // get the minimum number of jumps
    // needed to reach arr[h] from these
    // reachable points.
    int min = INT_MAX;
    for (int i = l + 1; i <= h && i <= l + arr[l]; i++) {
        int jumps = minJumps(arr, i, h);
        if (jumps != INT_MAX && jumps + 1 < min)
            min = jumps + 1;
    }

    return min;
}

// Driver program to test above function
int main()
{
    int arr[] = {1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9 };
    int n = sizeof(arr) / sizeof(arr[0]);
    printf("Minimum number of jumps to reach end is %d ",
           minJumps(arr, 0, n - 1));
    return 0;
}
Java
// Java program to find Minimum
// number of jumps to reach end
import java.io.*;
import java.util.*;

class GFG {
    // Returns minimum number of
    // jumps to reach arr[h] from arr[l]
    static int minJumps(int arr[], int l, int h)
    {
        // Base case: when source
        // and destination are same
        if (h == l)
            return 0;

        // When nothing is reachable
        // from the given source
        if (arr[l] == 0)
            return Integer.MAX_VALUE;

        // Traverse through all the points
        // reachable from arr[l]. Recursively
        // get the minimum number of jumps
        // needed to reach arr[h] from these
        // reachable points.
        int min = Integer.MAX_VALUE;
        for (int i = l + 1; i <= h && i <= l + arr[l];
             i++) {
            int jumps = minJumps(arr, i, h);
            if (jumps != Integer.MAX_VALUE
                && jumps + 1 < min)
                min = jumps + 1;
        }
        return min;
    }

    // Driver code
    public static void main(String args[])
    {
        int arr[] = { 1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9 };
        int n = arr.length;
        System.out.print(
            "Minimum number of jumps to reach end is "
            + minJumps(arr, 0, n - 1));
    }
}

// This code is contributed by Sahil_Bansall
Python
# Python3 program to find Minimum
# number of jumps to reach end

# Returns minimum number of jumps
# to reach arr[h] from arr[l]


def minJumps(arr, l, h):

    # Base case: when source and
    # destination are same
    if (h == l):
        return 0

    # when nothing is reachable
    # from the given source
    if (arr[l] == 0):
        return float('inf')

    # Traverse through all the points
    # reachable from arr[l]. Recursively
    # get the minimum number of jumps
    # needed to reach arr[h] from
    # these reachable points.
    min = float('inf')
    for i in range(l + 1, h + 1):
        if (i < l + arr[l] + 1):
            jumps = minJumps(arr, i, h)
            if (jumps != float('inf') and
                    jumps + 1 < min):
                min = jumps + 1

    return min


# Driver program to test above function
arr = [1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9]
n = len(arr)
print('Minimum number of jumps to reach',
      'end is', minJumps(arr, 0, n-1))

# This code is contributed by Soumen Ghosh
C#
// C# program to find Minimum
// number of jumps to reach end
using System;

class GFG {
    // Returns minimum number of
    // jumps to reach arr[h] from arr[l]
    static int minJumps(int[] arr, int l, int h)
    {
        // Base case: when source
        // and destination are same
        if (h == l)
            return 0;

        // When nothing is reachable
        // from the given source
        if (arr[l] == 0)
            return int.MaxValue;

        // Traverse through all the points
        // reachable from arr[l]. Recursively
        // get the minimum number of jumps
        // needed to reach arr[h] from these
        // reachable points.
        int min = int.MaxValue;
        for (int i = l + 1; i <= h && i <= l + arr[l];
             i++) {
            int jumps = minJumps(arr, i, h);
            if (jumps != int.MaxValue && jumps + 1 < min)
                min = jumps + 1;
        }
        return min;
    }

    // Driver code
    public static void Main()
    {
        int[] arr = { 1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9 };
        int n = arr.Length;
        Console.Write(
            "Minimum number of jumps to reach end is "
            + minJumps(arr, 0, n - 1));
    }
}

// This code is contributed by Sam007
JavaScript
// JavaScript program to find Minimum
// number of jumps to reach end

// Function to return the minimum number
// of jumps to reach arr[h] from arr[l]
function minJumps(arr, n)
{

    // Base case: when source and
    // destination are same
    if (n == 1)
        return 0;

    // Traverse through all the points
    // reachable from arr[l]
    // Recursively, get the minimum number
    // of jumps needed to reach arr[h] from
    // these reachable points
    let res = Number.MAX_VALUE;
    for (let i = n - 2; i >= 0; i--) {
        if (i + arr[i] >= n - 1) {
            let sub_res = minJumps(arr, i + 1);
            if (sub_res != Number.MAX_VALUE)
                res = Math.min(res, sub_res + 1);
        }
    }

    return res;
}

// Driver Code

let arr = [ 1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9 ];
let n = arr.length;
console.log("Minimum number of jumps to");
console.log(" reach end is " + minJumps(arr, n));
PHP
<?php
// php program to find Minimum 
// number of jumps to reach end

// Returns minimum number of jumps 
// to reach arr[h] from arr[l]
function minJumps($arr, $l, $h)
{
    
    // Base case: when source and
    // destination are same
    if ($h == $l)
        return 0;
    
    // When nothing is reachable
    // from the given source
    if ($arr[$l] == 0)
        return $h+1;
    
    // Traverse through all the points 
    // reachable from arr[l]. Recursively
    // get the minimum number of jumps
    // needed to reach arr[h] from these
    // reachable points.
    $min = 999999;
    
    for ($i = $l+1; $i <= $h && 
             $i <= $l + $arr[$l]; $i++)
    {
        $jumps = minJumps($arr, $i, $h);
        
        if($jumps != 999999 && 
                     $jumps + 1 < $min)
            $min = $jumps + 1;
    }
    
    return $min;
}

// Driver program to test above function
$arr = array(1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9);
$n = count($arr);

echo "Minimum number of jumps to reach "
     . "end is ". minJumps($arr, 0, $n-1);
    
// This code is contributed by Sam007
?>

Output
Minimum number of jumps to reach the end is 3

Time complexity: O(nn). There are maximum n possible ways to move from an element.  So the maximum number of steps can be nn.
Auxiliary Space: O(n). For recursion call stack. 

Using Dynamic Programming (Memoization):

It can be observed that there will be overlapping subproblems. 

For example in array, arr[] = {1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9} minJumps(3, 9) will be called two times as arr[3] is reachable from arr[1] and arr[2]. So this problem has both properties (optimal substructure and overlapping subproblems) of Dynamic Programming.

Follow the below steps to implement the idea:

  • Create memo[] such that memo[i] indicates the minimum number of jumps needed to reach memo[n-1] from memo[i] to store previously solved subproblems.
  • During the recursion call, if the same state is called more than once, then we can directly return the answer stored for that state instead of calculating again.
  • Otherwise, In each recursive call get all the reachable nodes from that index.
    • For each of the index call the recursive function.
    • Find the minimum number of jumps to reach the end from current index.
C++
#include <bits/stdc++.h>
using namespace std;

 int jump(vector<int>& nums, int idx, int end, vector<int>& memo) {
        
        //we reached the end. No jumps to make further
        if (idx == end)
            return 0;
        
        if (memo[idx] != -1)
            return memo[idx];
        
        int min_jumps = INT_MAX - 1;
        
        //we will try to make all possible jumps from current index
        //and select the minimum of those
        //It does not matter if we try from 1 to nums[idx]
        //or from nums[idx] to 1
        for (int j = nums[idx]; j >= 1; --j) {
          
            //If we make this jump 'j' distance away from idx
            //do we overshoot?
            //if we land within the nums, we will test further
            if (idx + j <= end) {
              
                //Make a jump to idx + j index and explore further
                //then update min_jumps with the minimum jumps
                //we made to reach end while trying all possible
                //nums[idx] jumps from current index.
                min_jumps = min(min_jumps, 
                                1 + jump(nums, idx + j, end, memo));
            }
        }
        
        return memo[idx] = min_jumps;
    }
    
    //Memoization
    int minJumps(vector<int>& nums) {
        vector<int> memo(nums.size(), -1);
        return jump(nums, 0, nums.size() - 1, memo);
    }


int main()
{
    int n = 11;
    vector<int> arr{ 1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9 };
    cout << minJumps(arr) << endl;

    return 0;
}

// This code is contributed by Tushar Seth
C
#include <stdio.h>
#include <limits.h>

int min(int a, int b) {return (a < b) ? a : b;}

int jump(int nums[], int idx, int end, int memo[]) {

    // We reached the end. No jumps to make further
    if (idx == end)
        return 0;

    if (memo[idx] != -1)
        return memo[idx];

    int min_jumps = INT_MAX - 1;

    // We will try to make all possible jumps from current index
    // and select the minimum of those
    for (int j = nums[idx]; j >= 1; --j) {

        // If we make this jump 'j' distance away from idx
        // do we overshoot?
        // If we land within the nums, we will test further
        if (idx + j <= end) {

            // Make a jump to idx + j index and explore further
            // then update min_jumps with the minimum jumps
            // we made to reach end while trying all possible
            // nums[idx] jumps from current index.
            min_jumps = min(min_jumps, 
                            1 + jump(nums, idx + j, end, memo));
        }
    }

    return memo[idx] = min_jumps;
}

// Memoization
int minJumps(int nums[], int n) {
    int memo[n];
    for (int i = 0; i < n; ++i)
        memo[i] = -1;
    return jump(nums, 0, n - 1, memo);
}

int main() {
    int n = 11;
    int arr[] = { 1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9 };
    printf("%d\n", minJumps(arr, n));

    return 0;
}
Java
import java.util.Arrays;

public class Geek {

    // Helper function to find the minimum jumps required to reach the end
    private static int jump(int[] nums, int idx, int end, int[] memo) {

        // We reached the end. No jumps to make further
        if (idx == end)
            return 0;

        if (memo[idx] != -1)
            return memo[idx];

        int min_jumps = Integer.MAX_VALUE - 1;

        // We will try to make all possible jumps from the current index
        // and select the minimum of those.
        // It does not matter if we try from 1 to nums[idx] or from nums[idx] to 1.
        for (int j = nums[idx]; j >= 1; --j) {
            // If we make this jump 'j' distance away from idx,
            // do we overshoot?
            // If we land within the nums, we will test further.
            if (idx + j <= end) {
                // Make a jump to idx + j index and explore further,
                // then update min_jumps with the minimum jumps
                // we made to reach the end while trying all possible
                // nums[idx] jumps from the current index.
                min_jumps = Math.min(min_jumps, 1 + jump(nums, idx + j, end, memo));
            }
        }

        return memo[idx] = min_jumps;
    }

    // Memoization
    private static int minJumps(int[] nums) {
        int[] memo = new int[nums.length];
        Arrays.fill(memo, -1);
        return jump(nums, 0, nums.length - 1, memo);
    }

    public static void main(String[] args) {
        int[] arr = {1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9};
        System.out.println(minJumps(arr));
    }
}
Python
# Helper function to find the minimum jumps required to reach the end
def jump(nums, idx, end, memo):
    # We reached the end. No jumps to make further
    if idx == end:
        return 0

    if memo[idx] != -1:
        return memo[idx]

    min_jumps = float("inf")

    # We will try to make all possible jumps from the current index
    # and select the minimum of those.
    # It does not matter if we try from 1 to nums[idx] or from nums[idx] to 1.
    for j in range(nums[idx], 0, -1):
        # If we make this jump 'j' distance away from idx,
        # do we overshoot?
        # If we land within the nums, we will test further.
        if idx + j <= end:
            # Make a jump to idx + j index and explore further,
            # then update min_jumps with the minimum jumps
            # we made to reach the end while trying all possible
            # nums[idx] jumps from the current index.
            min_jumps = min(min_jumps, 1 + jump(nums, idx + j, end, memo))

    memo[idx] = min_jumps
    return memo[idx]


def min_jumps(nums):
    """Memoization"""

    memo = [-1 for i in range(len(nums))]
    jump(nums, 0, len(nums) - 1, memo)
    return memo[0]


if __name__ == "__main__":
    arr = [1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9]
    print(min_jumps(arr))
# this code is contributed by Rohit Singh
C#
using System;

class JumpGame {
    // Recursive function to find minimum jumps required to
    // reach the end
    static int Jump(int[] nums, int idx, int end,
                    int[] memo)
    {
        // We reached the end, no more jumps needed
        if (idx == end)
            return 0;

        // If memoization contains a value, return it
        if (memo[idx] != -1)
            return memo[idx];

        int minJumps = int.MaxValue - 1;

        // Try all possible jumps from the current index
        for (int j = nums[idx]; j >= 1; j--) {
            // Check if making the jump 'j' distance away
            // from idx overshoots the end
            if (idx + j <= end) {
                // Make the jump to idx + j index and
                // explore further Update minJumps with the
                // minimum jumps to reach the end
                minJumps = Math.Min(
                    minJumps,
                    1 + Jump(nums, idx + j, end, memo));
            }
        }

        // Memoize the result and return it
        return memo[idx] = minJumps;
    }

    // Memoization function to find minimum jumps
    static int MinJumps(int[] nums)
    {
        int[] memo = new int[nums.Length];
        Array.Fill(memo, -1);
        return Jump(nums, 0, nums.Length - 1, memo);
    }

    static void Main()
    {
        int[] arr = { 1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9 };
        Console.WriteLine(MinJumps(arr));
    }
}
JavaScript
function jump(nums, idx, end, memo) {
    // We reached the end. No jumps to make further.
    if (idx === end)
        return 0;

    if (memo[idx] !== -1)
        return memo[idx];

    let min_jumps = Number.MAX_SAFE_INTEGER - 1;

    // We will try to make all possible jumps from the current index
    // and select the minimum of those.
    // It does not matter if we try from 1 to nums[idx] or from nums[idx] to 1.
    for (let j = nums[idx]; j >= 1; --j) {
        // If we make this jump 'j' distance away from idx,
        // do we overshoot?
        // If we land within the nums, we will test further.
        if (idx + j <= end) {
            // Make a jump to idx + j index and explore further,
            // then update min_jumps with the minimum jumps
            // we made to reach the end while trying all possible
            // nums[idx] jumps from the current index.
            min_jumps = Math.min(min_jumps, 1 + jump(nums, idx + j, end, memo));
        }
    }

    return memo[idx] = min_jumps;
}

function minJumps(nums) {
    const memo = Array(nums.length).fill(-1);
    return jump(nums, 0, nums.length - 1, memo);
}

const arr = [1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9];
console.log(minJumps(arr));

Output
3

Time complexity: O(n^2) as for each position i the recursive function is called once and a loop runs for O(n) for each position in the worst case denoting the number of reachable positions from position i.
Auxiliary Space: O(n), because of recursive stack space and memo array.

Using Dynamic Programming (Tabulation):

Follow the below steps to implement the idea:

  • Create jumps[] array from left to right such that jumps[i] indicate the minimum number of jumps needed to reach arr[i] from arr[0].
  • To fill the jumps array run a nested loop inner loop counter is j and the outer loop count is i.
    • Outer loop from 1 to n-1 and inner loop from 0 to i.
    • If i is less than j + arr[j] then set jumps[i] to minimum of jumps[i] and jumps[j] + 1. initially set jump[i] to INT MAX
  • Return jumps[n-1].

Below is the implementation of the above approach:

C++
#include <bits/stdc++.h>
using namespace std;

// Returns minimum number of jumps to reach
// arr[n-1] from arr[0]
int minJumps(vector<int>& arr) {
    int n = arr.size();

    // jumps[n-1] will hold the result
    vector<int> jumps(n, INT_MAX);
    
    if (n == 0 || arr[0] == 0)
        return INT_MAX;

    jumps[0] = 0;

    // Find the minimum number of jumps to 
    // reach arr[i] from arr[0],
    // and assign this value to jumps[i]
    for (int i = 1; i < n; i++) {
        for (int j = 0; j < i; j++) {
            if (i <= j + arr[j] && jumps[j] != INT_MAX) {
                jumps[i] = min(jumps[i], jumps[j] + 1);
                break;
            }
        }
    }
    return jumps[n - 1];
}

// Driver code
int main() {
    vector<int> arr = { 1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9 };
    cout << "Minimum number of jumps to reach end is "
         << minJumps(arr) << endl;
    return 0;
}
C
// C program for Minimum number
// of jumps to reach end
#include <limits.h>
#include <stdio.h>

int min(int x, int y) { return (x < y) ? x : y; }

// Returns minimum number of
// jumps to reach arr[n-1] from arr[0]
int minJumps(int arr[], int n)
{
    // jumps[n-1] will hold the result
    int jumps[n];
    int i, j;

    if (n == 0 || arr[0] == 0)
        return INT_MAX;

    jumps[0] = 0;

    // Find the minimum number of
    // jumps to reach arr[i]
    // from arr[0], and assign this
    // value to jumps[i]
    for (i = 1; i < n; i++) {
        jumps[i] = INT_MAX;
        for (j = 0; j < i; j++) {
            if (i <= j + arr[j] && jumps[j] != INT_MAX) {
                jumps[i] = min(jumps[i], jumps[j] + 1);
                break;
            }
        }
    }
    return jumps[n - 1];
}

// Driver program to test above function
int main()
{
    int arr[] = { 1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9 };
    int size = sizeof(arr) / sizeof(int);
    printf("Minimum number of jumps to reach end is %d ",
           minJumps(arr, size));
    return 0;
}
Java
// JAVA Code for Minimum number
// of jumps to reach end

import java.io.*;

class GFG {

    private static int minJumps(int[] arr, int n)
    {
        // jumps[n-1] will hold the
        int jumps[] = new int[n];
        // result
        int i, j;

        // if first element is 0,
        if (n == 0 || arr[0] == 0)
            return Integer.MAX_VALUE;
        // end cannot be reached

        jumps[0] = 0;

        // Find the minimum number of jumps to reach arr[i]
        // from arr[0], and assign this value to jumps[i]
        for (i = 1; i < n; i++) {
            jumps[i] = Integer.MAX_VALUE;
            for (j = 0; j < i; j++) {
                if (i <= j + arr[j]
                    && jumps[j] != Integer.MAX_VALUE) {
                    jumps[i]
                        = Math.min(jumps[i], jumps[j] + 1);
                    break;
                }
            }
        }
        return jumps[n - 1];
    }

    // driver program to test above function
    public static void main(String[] args)
    {
        int arr[] = { 1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9 };

        System.out.println(
            "Minimum number of jumps to reach end is : "
            + minJumps(arr, arr.length));
    }
}

// This code is contributed by Arnav Kr. Mandal.
Python
# Python3 program to find Minimum
# number of jumps to reach end

# Returns minimum number of jumps
# to reach arr[n-1] from arr[0]


def minJumps(arr, n):
    jumps = [0 for i in range(n)]

    if (n == 0) or (arr[0] == 0):
        return float('inf')

    jumps[0] = 0

    # Find the minimum number of
    # jumps to reach arr[i] from
    # arr[0] and assign this
    # value to jumps[i]
    for i in range(1, n):
        jumps[i] = float('inf')
        for j in range(i):
            if (i <= j + arr[j]) and (jumps[j] != float('inf')):
                jumps[i] = min(jumps[i], jumps[j] + 1)
                break
    return jumps[n-1]


# Driver Program to test above function
arr = [1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9]
size = len(arr)
print('Minimum number of jumps to reach',
      'end is', minJumps(arr, size))

# This code is contributed by Soumen Ghosh
C#
// C# Code for Minimum number of jumps to reach end
using System;

class GFG {
    static int minJumps(int[] arr, int n)
    {
        // jumps[n-1] will hold the
        // result
        int[] jumps = new int[n];

        // if first element is 0,
        if (n == 0 || arr[0] == 0)

            // end cannot be reached
            return int.MaxValue;

        jumps[0] = 0;

        // Find the minimum number of
        // jumps to reach arr[i]
        // from arr[0], and assign
        // this value to jumps[i]
        for (int i = 1; i < n; i++) {
            jumps[i] = int.MaxValue;
            for (int j = 0; j < i; j++) {
                if (i <= j + arr[j]
                    && jumps[j] != int.MaxValue) {
                    jumps[i]
                        = Math.Min(jumps[i], jumps[j] + 1);
                    break;
                }
            }
        }
        return jumps[n - 1];
    }

    // Driver program
    public static void Main()
    {
        int[] arr = { 1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9 };
        Console.Write(
            "Minimum number of jumps to reach end is : "
            + minJumps(arr, arr.Length));
    }
}

// This code is contributed by Sam007
JavaScript
function minJumps(arr) {
    let n = arr.length;

    // If the array is empty or the first 
    // element is 0, return Infinity
    if (n === 0 || arr[0] === 0) {
        return Infinity;
    }

    // jumps[n-1] will hold the result
    let jumps = new Array(n).fill(Infinity);
    jumps[0] = 0;

    // Find the minimum number of jumps to 
    // reach arr[i] from arr[0],
    // and assign this value to jumps[i]
    for (let i = 1; i < n; i++) {
        for (let j = 0; j < i; j++) {
            if (i <= j + arr[j] && jumps[j] !== Infinity) {
                jumps[i] = Math.min(jumps[i], jumps[j] + 1);
                break;
            }
        }
    }
    return jumps[n - 1];
}

// Driver code
let arr = [1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9];
console.log("Minimum number of jumps to reach end is " + minJumps(arr));
PHP
<?php
// PHP code for Minimum number of
// jumps to reach end

// Returns minimum number of jumps
// to reach arr[n-1] from arr[0]
function minJumps($arr, $n)
{
    // jumps[n-1] will
    // hold the result
    $jumps = array($n);
    
    if ($n == 0 || $arr[0] == 0)
        return 999999;

    $jumps[0] = 0;

    // Find the minimum number of
    // jumps to reach arr[i]
    // from arr[0], and assign 
    // this value to jumps[i]
    for ($i = 1; $i < $n; $i++)
    {
        $jumps[$i] = 999999;
        for ($j = 0; $j < $i; $j++)
        {
            if ($i <= $j + $arr[$j] && 
                $jumps[$j] != 999999)
            {
                $jumps[$i] = min($jumps[$i], 
                             $jumps[$j] + 1);
                break;
            }
        }
    }
    return $jumps[$n-1];
}

    // Driver Code
    $arr = array(1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9);
    $size = count($arr);
    echo "Minimum number of jumps to reach end is ". 
                             minJumps($arr, $size);
                             
// This code is contributed by Sam007
?>

Output
Minimum number of jumps to reach end is 3

Time Complexity: O(n2) 
Auxiliary Space: O(n), since n extra space has been taken.

Refer to the article given below to solve this problem in O(n) time:

Minimum number of jumps to reach end | Set 2 (O(n) solution)



Previous Article
Next Article

Similar Reads

Check if end of a sorted Array can be reached by repeated jumps of one more, one less or same number of indices as previous jump
Given a sorted array arr[] of size N, the task is to check if it is possible to reach the end of the given array from arr[1] by jumping either arr[i] + k - 1, arr[i] + k, or arr[i] + k + 1 in each move, where k represents the number of indices jumped in the previous move. Consider K = 1 initially. If it is possible, then print "Yes". Otherwise, pri
11 min read
Minimize cost to reach end of an array by two forward jumps or one backward jump in each move
Given an array arr[] consisting of N positive integers, the task is to find the minimum cost required to either cross the array or reach the end of the array by only moving to indices (i + 2) and (i - 1) from the ith index. Examples: Input: arr[] = {5, 1, 2, 10, 100}Output: 18Explanation:Optimal cost path (0 based indexing): 0 ? 2 ? 1 ? 3 ? 5Theref
11 min read
Maximum jumps to reach end of Array with condition that index i can make arr[i] jumps
Given an integer N and an array arr[ ] of size N, the task is to find the maximum jumps to reach the end of the array given the constraint that from index i can make arr[i] jumps and reach the position i+arr[i]. Examples: Input: N = 5, arr[] = {2, 3, 5, 7, 9}Output: 12 Explanation:At index 0 make 2 jumps and move to index 2 and make 5 jumps after t
6 min read
Find the minimum of maximum length of a jump required to reach the last island in exactly k jumps
Given an array arr[] of integers, where the ith integer represents the position where an island is present, and an integer k (1 ? k &lt; N). A person is standing on the 0th island and has to reach the last island, by jumping from one island to another in exactly k jumps, the task is to find the minimum of the maximum length of a jump a person will
9 min read
Minimum jumps to traverse all integers in range [1, N] such that integer i can jump i steps
Given an integer N, the task is to find the minimum steps to visit all integers in the range [1, N] by selecting any integer and jump i steps at every ith jump. Note: It is possible to revisit an integer more than once. Examples: Input: N = 6Output: 3Explanation: One of the following way is: First start at first number and visit the integers {1, 2,
7 min read
Find position after K jumps from start of given Array where each jump is from i to arr[i]
Given an array arr[] of size N containing elements from 1 to N. Find the position after exactly K jumps from index 1 where the jump from ith index sends to arr[i] index. Examples: Input: arr[ ] = { 3, 2, 4,1 }, K = 5;Output: 4Explanation: Start from index 1 and go to position 3 -&gt; 4 -&gt;1 -&gt; 3 -&gt; 4 Input: arr[ ] = { 3 , 2 , 1 }, K = 3Outp
7 min read
Minimum cost to reach end of array when a maximum jump of K index is allowed
Given an array arr[] of N integers and an integer K, one can move from an index i to any other j if j &lt;= i + k. The cost of moving from one index i to the other index j is abs(arr[i] - arr[j]). Initially, we start from the index 0 and we need to reach the last index i.e. N - 1. The task is to reach the last index in the minimum cost possible.Exa
12 min read
Minimum number of Fibonacci jumps to reach end
Given an array of 0s and 1s, If any particular index i has value 1 then it is a safe index and if the value is 0 then it is an unsafe index. A man is standing at index -1(source) can only land on a safe index and he has to reach the Nth index (last position). At each jump, the man can only travel a distance equal to any Fibonacci Number. You have t
11 min read
Count minimum factor jumps required to reach the end of an Array
Given an array of positive integers arr[], the task is to count the minimum factor jumps required to reach the end of an array. From any particular index i, the jump can be made only for K indices where K is a factor of arr[i]. Examples: Input: arr[] = {2, 8, 16, 55, 99, 100} Output: 2 Explanation: The optimal jumps are: a) Start from 2. b) Since f
15+ min read
Paths requiring minimum number of jumps to reach end of array
Given an array arr[], where each element represents the maximum number of steps that can be made forward from that element, the task is to print all possible paths that require the minimum number of jumps to reach the end of the given array starting from the first array element. Note: If an element is 0, then there are no moves allowed from that el
12 min read
Minimum cost to reach the end of the array with maximum jumps of length K
Given an array arr[] of size N and an integer K, one can move from an index i to any other index j such that j ? i+k. The cost of being at any index 'i', is arr[i]. The task is to find the minimum cost to reach the end of the array starting from index 0. Examples: Input : arr[] = {2, 4, 1, 6, 3}, K = 2Output: 6Explanation: Path can be taken as 2 -
11 min read
Minimum jumps from either end to reach largest and smallest character in given String
Given a string str, the task is to find the minimum number of moves required to reach lexicographically largest and smallest characters. In one move, a jump can be made from leftmost side or the rightmost side of given string. Examples: Input: str = AEDCB, N = 5 Output: 2Explanation: take two steps from leftmost side to reach A and E Input: str = B
6 min read
Minimum jumps to same value or adjacent to reach end of Array
Given an array arr[] of size N, the task is to find the minimum number of jumps to reach the last index of the array starting from index 0. In one jump you can move from current index i to index j, if arr[i] = arr[j] and i != j or you can jump to (i + 1) or (i – 1). Note: You can not jump outside of the array at any time. Examples: Input: arr = {10
14 min read
Minimum number of jumps to reach end | Set 2 (O(n) solution)
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). If an element is 0, then we cannot move through that element. If we can't reach the end, return -1.Prereq
13 min read
Minimum jumps to reach end of the array with given conditions
Given an array A[], the task is to print the minimum number of jumps needed to reach the last element of A[] starting from the first element. If it is impossible to reach the last element print -1. A jump can be made from index i to j if all the below conditions are met: i &lt; jA[i] &gt;= A[j]There must be no elements between index i and j or all
6 min read
Game Theory (Normal form game) | Set 2 (Game with Pure Strategy)
Game Theory (Normal – form game) | Set 1 (Introduction) Please go through the above article before proceeding. Given a payoff matrix. The task is to find the optimum strategies of the players. Solution: Player A is having 3 strategies - 1, 2 and 3, and player B is also having 3 strategies - 1, 2 and 3. Step 1: Find row minimum values for each row a
2 min read
Game Theory (Normal-form game) | Set 3 (Game with Mixed Strategy)
Consider the following payoff matrix with respect to player A and solve it optimally. Solution: If a game has no saddle point then the game is said to have mixed strategy. Step 1: Find out the row minimum and column maximum. Step 2: Find out the minimax and maximin values. Since minimax and maximin value of this game are not equal, this game has no
4 min read
Game Theory (Normal-form Game) | Set 7 (Graphical Method [M X 2] Game)
The payoff matrix of an M * 2 game consists of M rows and two columns. This article will discuss how to solve an M * 2 game by graphical method. Also, this article will discuss if more than two lines intersect the same point in the graph then how can a 2 * 2 payoff matrix be formed. Consider the below problem: Solution: First check whether the prob
3 min read
Game Theory (Normal-form Game) | Set 6 (Graphical Method [2 X N] Game)
The payoff matrix of a 2 * N game consists of 2 rows and N columns . This article will discuss how to solve a 2 * N game by graphical method. Consider the below 2 * 5 game: Solution: First check the saddle point of the game. This game has no saddle point. Step 1: Reduce the size of the payoff matrix by applying dominance property, if it exists. Thi
3 min read
Jump Game III Problem
Given an array arr[] of non-negative integers size N, the task is to start from index X and check if we can reach any index with value 0. For any index i, we can jump to i + arr[i] or i - arr[i]. Note: We cannot jump outside the array at any time. Examples: Input: arr[] = {4, 2, 3, 0, 3, 1, 2}, X = 5Output: trueExplanation: It is possible to reach
5 min read
Count number of ways to jump to reach end
Given an array of numbers where each element represents the max number of jumps that can be made forward from that element. For each array element, count the number of ways jumps can be made from that element to reach the end of the array. If an element is 0, then a move cannot be made through that element. The element that cannot reach the end sho
14 min read
Maximum power of jump required to reach the end of string
Given a string consisting of 1 and 0, the task is to find out the maximum power of jump required to reach the end of the string. At a time you can jump from one 1 to the next 1 or from one 0 to the next 0. Note: Power of jump is defined as the distance between two consecutive 1's or two consecutive 0's. Examples: Input: 10101 Output: 2 First, make
7 min read
Check if end of given Binary string can be reached by choosing jump value in between given range
Given two positive integers L and R and a binary string S of size N, the task is to check if the end of the string is reached from the index 0 by a series of jumps of indices, say i such that S[i] is 0 jumps are allowed in the range [L, R]. If it is possible to reach, then print Yes. Otherwise, print No. Examples: Input: S = "011010", L = 2, R = 3O
7 min read
Minimize cost to reach the end of given Binary Array using jump of K length after performing given operations
Given a binary array arr[] of N integers and an integer P, the task is to find the minimum cost to reach the end of the array from Pth index using jumps of length K. A jump to index i is valid if arr[i] = 1. The array can be modified using the following operations: Replace an index having a value 0 to 1. The cost of this operation is X.Delete the i
8 min read
Count of jumps to reach the end of Array by jumping from arr[i] to arr[arr[i]]
Given an array arr[] of N integers, the task is to find the number of jumps required to escape the array arr[] for all values of i as the starting indices in the range [0, N) where the only possible jump from arr[i] is to arr[arr[i]] and escaping the array means arr[i]&gt;=N, i.e, the index for the next jump does not exist. Examples: Input: arr[] =
10 min read
Minimise jumps to reach end of Array by jumping in range [x, x+k]
Given an array arr[] of size N and an integer k. Return True, otherwise False, if there's any way to reach the last element of arr[] by satisfying the following conditions: Only move in the forward direction.Initially, we can increase only by 1 from the first element.We are allowed to increment by x + 1, x + 2, x + 3....., x+ k, where x is the last
7 min read
Count ways to reach end from start stone with at most K jumps at each step
Given N stones in a row from left to right. From each stone, you can jump to at most K stones. The task is to find the total number of ways to reach from sth stone to Nth stone. Examples: Input: N = 5, s = 2, K = 2 Output: Total Ways = 3 Explanation: Assume s1, s2, s3, s4, s5 be the stones. The possible paths from 2nd stone to 5th stone: s2 -&gt; s
7 min read
Minimum length of jumps to avoid given array of obstacles
We are given coordinates of obstacles on a straight line. We start jumping from point 0, we need to reach the end, avoiding all obstacles. The length of every jump has to be the same (For example, if we jump from 0 to 4, then we must make the next jump from 4 to 8). We need to find the minimum length of the jump so that we can reach the end and we
5 min read
Minimum jumps required to group all 1s together in a given Binary string
Given a binary string S, the task is to count the minimum number of jumps required to group all 1's together. Examples: Input: S = "000010011000100" Output: 5 Explanation: 000010011000100 -&gt; 000000111000100 requires 2 jumps. 000000111000100 -&gt; 000000111100000 requires 3 jumps. Hence, at least 5 jumps are required to group all 1's together. In
6 min read
Minimum jumps required to make a group of persons sit together
Given a string S of length N consisting of 'x' and '.'. The given string represents a row of seats where 'x' and '.' represent occupied and unoccupied seats respectively. The task is to minimize the total number of hops or jumps to make all the occupants sit together i.e., next to each other, without having any vacant seat between them. Note: Since
8 min read
three90RightbarBannerImg