minimum no of jump required to reach end of arry

#include <iostream>
#include <climits>
using namespace std;

int minJumps(int arr[], int n) {
    if (n <= 1)
        return 0;

    if (arr[0] == 0)
        return -1;

    int maxReach = arr[0];
    int steps = arr[0];
    int jumps = 1;

    for (int i = 1; i < n; i++) {
        if (i == n - 1)
            return jumps;

        maxReach = max(maxReach, i + arr[i]);
        steps--;

        if (steps == 0) {
            jumps++;

            if (i >= maxReach)
                return -1;

            steps = maxReach - i;
        }
    }

    return -1;
}

int main() {
    int arr[] = {2, 3, 1, 1, 4};
    int size = sizeof(arr) / sizeof(arr[0]);

    int result = minJumps(arr, size);

    if (result != -1)
        cout << "Minimum number of jumps required: " << result << endl;
    else
        cout << "Cannot reach the end of the array" << endl;

    return 0;
}

Explanation:

  1. minJumps function takes an array arr and its size n as input parameters.
  2. It checks if the array has one or fewer elements, in which case it returns 0 jumps (no jumps required to reach the end).
  3. It checks if the first element of the array is 0, indicating an inability to move forward, in which case it returns -1.
  4. It initializes variables maxReach, steps, and jumps to keep track of the maximum reachable index, steps remaining at the current index, and the total number of jumps taken, respectively.
  5. It iterates through the array starting from the second element.
  6. Inside the loop, it updates maxReach to the maximum of its current value and the sum of the current index i and the value at that index arr[i].
  7. Decrements steps as the loop progresses.
  8. Checks if steps becomes 0, indicating the necessity to take a jump. It increments jumps.
  9. If the index i has exceeded maxReach, it means there is no way to move forward, so it returns -1.
  10. Updates steps to the difference between maxReach and the current index i.
  11. Continues the loop until the end of the array is reached or it determines it cannot reach the end.
  12. In the main function, it initializes an example array arr and calculates the minimum number of jumps required by calling the minJumps function.
  13. If the result is not -1, it displays the minimum number of jumps required; otherwise, it indicates that it's impossible to reach the end of the array.