Program for ARRAY JUMPER
Thu Sep 12 2024 06:26:22 GMT+0000 (Coordinated Universal Time)
Saved by
@Rohan@99
#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;
}
content_copyCOPY
Comments