xxxxxxxxxx
let jump = 0
let curr = 0
let res = 0
for(let i=0; i<n-1; i++){
res=Math.max(res,arr[i]+i);
if(curr==i){
curr=res;
jump++;
}
}
if(curr>=(n-1)){
return jump;
} else {
return -1;
}
xxxxxxxxxx
class Solution868
{
//Function to find minimum number of jumps to reach the end of the array.
public static int minimumJumps(int arr[], int n)
{
// your code here
int jumps = 0;
int curr = 0;
int max = 0;
for(int i=0;i<n-1;i++)
{
max = Math.max(max, i+arr[i]);
if(curr == i)
{
jumps++;
curr = max;
}
}
return curr >= n-1 ? jumps: -1;
}
}
xxxxxxxxxx
#include <iostream>
using namespace std;
int getMinSteps(int arr[], int n)
{
int jump = 0;
for (int i = 0; i < n - 1; i = i + arr[i])
{
if (arr[i] == 0)
return -1;
jump++;
}
return jump;
}
int main()
{
int arr[] = {1, 0, 2};
int size = sizeof(arr) / sizeof(arr[0]);
cout << getMinSteps(arr, size);
}