Preview:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int min_jumps(int nums[], int n) 
{
    if (n <= 1) {
        return 0; // No jumps needed if the array has only one element
    }
    
    // Initialize variables
    int jumps = 0;
    int farthest = 0;
    int current_end = 0;

    for (int i = 0; i < n - 1; i++) 
    {
        // Update the farthest we can reach
        farthest = max(farthest, i + nums[i]);

        // When we reach the end of the current range, we must jump
        if (i == current_end) 
        {
            jumps++;
            current_end = farthest;

            // If we can already reach the last index, break early
            if (current_end >= n - 1) 
            {
                break;
            }
        }
    }

    return jumps;
}

int main() 
{
    int n;
    cout << "Enter the size of the array: ";
    cin >> n;
    
    int nums[n];
    cout << "Enter the elements of the array: ";
    for (int i = 0; i < n; i++) 
    {
        cin >> nums[i];
    }
    
    int result = min_jumps(nums, n);
    cout << "Minimum number of jumps to reach the last index: " << result << endl;

    return 0;
}
downloadDownload PNG downloadDownload JPEG downloadDownload SVG

Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!

Click to optimize width for Twitter