Question:
How to find the minimum number of jumps to reach the end of the array using C++

Summary

Lets assume:

Array- arr

Integer- N

Function- minJumps()


Solution

// Function to return minimum number of jumps to end of array


class Solution{

  public:

    int minJumps(int arr[], int n){

        

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

        if(n == 1) return 0;

        

        int steps = arr[0];

        int maxReach = arr[0];

        int jumps = 1;

        

          for(int i = 1; i<n; i++){

            

            if(i == n-1) return jumps;

            

            // Ab apan agle point par aagye to maxReach nikalo aur store kralo

            if(steps) {

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

            

             // Ab apan agle point pr aagye hai to ek step kam kardo

             steps--;

            }

            

            // check kro ki steps khatm to nhi ho gye

            if(steps == 0){

                

                // agar end point tak pahuchne se pahale koi zero mil gya aur usse pahale koi maxReach nhi tha

                if(i>=maxReach) return -1;

                

                // steps khatm hue matlab new point par aagye

                // yha se bhi jump lga do

                // apan jump tabhi lagayenge jab steps khatm ho jayenge

                jumps++;

                

                // steps ko update krlo

                steps = maxReach - i;

            }

        }

        

        return -1;

    }

};


Answered by:> >_uncle_sam_055_

Credit:> >GeekforGeeks


Suggested blogs:

>How to configure python in jmeter?

>How to mock a constant value in Python?

>Creating a pivot table by 6 month interval rather than year

>How to Install mariaDB client efficiently inside docker?

>Can I call an API to find out the random seed in Python `hash()` function?

>How remove residual lines after merge two regions using Geopandas in python?


Submit
0 Answers

What Our Clients Say About Us

Client satisfaction is our ultimate goal. Here are some kind words of our precious clients they have used to express their satisfaction with our service.

Why Choose Us ?

We endow businesses with flexible engagement models based on their unique needs. Our strength lies in state-of-the-art technology and affordable consulting services. Try us for fast POCs, full-fledged applications, or technology consulting. Always available for your service.