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:
minJumps
function takes an arrayarr
and its sizen
as input parameters.- It checks if the array has one or fewer elements, in which case it returns 0 jumps (no jumps required to reach the end).
- It checks if the first element of the array is 0, indicating an inability to move forward, in which case it returns -1.
- It initializes variables
maxReach
,steps
, andjumps
to keep track of the maximum reachable index, steps remaining at the current index, and the total number of jumps taken, respectively. - It iterates through the array starting from the second element.
- Inside the loop, it updates
maxReach
to the maximum of its current value and the sum of the current indexi
and the value at that indexarr[i]
. - Decrements
steps
as the loop progresses. - Checks if
steps
becomes 0, indicating the necessity to take a jump. It incrementsjumps
. - If the index
i
has exceededmaxReach
, it means there is no way to move forward, so it returns -1. - Updates
steps
to the difference betweenmaxReach
and the current indexi
. - Continues the loop until the end of the array is reached or it determines it cannot reach the end.
- In the
main
function, it initializes an example arrayarr
and calculates the minimum number of jumps required by calling theminJumps
function. - 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.