Minimum no. of Jumps to reach end of an array

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

Constraints:

1 ≤ N ≤ 107
0 <= ai <= 107


//Here we have given the function only

1:  int jump(vector<int>& nums)   
2:    {  
3:    int jump = 0, pos = 0, des = 0, n = nums.size() - 1;  
4:    for (int i = 0; i < n; i++)   
5:    {  
6:     des = max(des, i + nums[i]);  
7:     if (pos == i)   
8:     {  
9:      pos = des;  
10:      jump++;  
11:     }  
12:    }  
13:    return jump;  
14:    }  

Post a Comment

0 Comments