Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C Program for Minimum number of jumps to reach the end
The minimum jumps problem involves finding the minimum number of jumps needed to reach the last index of an array from the first index. Each element in the array represents the maximum number of steps that can be taken forward from that position.
Syntax
int minJumps(int arr[], int n);
Algorithm
The naive approach starts from the first element and recursively calculates the minimum jumps needed −
minJumps(start, end) = Min(minJumps(k, end)) for all k accessible from start
We use dynamic programming with bottom-up approach. For each position, we check all previous positions that can reach the current position and take the minimum jumps.
Example: Dynamic Programming Approach
This solution has O(n²) time complexity and O(n) space complexity −
#include <stdio.h>
#include <limits.h>
int minJumps(int arr[], int n) {
int steps[n];
int i, j;
if (n == 0 || arr[0] == 0)
return INT_MAX;
steps[0] = 0;
for (i = 1; i < n; i++) {
steps[i] = INT_MAX;
for (j = 0; j < i; j++) {
if (i <= j + arr[j] && steps[j] != INT_MAX) {
steps[i] = (steps[i] < (steps[j] + 1)) ? steps[i] : steps[j] + 1;
break;
}
}
}
return steps[n - 1];
}
int main() {
int arr[] = {2, 1, 1, 5, 2, 1, 1};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("<br>");
int result = minJumps(arr, n);
if (result == INT_MAX) {
printf("Cannot reach the end<br>");
} else {
printf("Minimum number of jumps: %d<br>", result);
}
return 0;
}
Array: 2 1 1 5 2 1 1 Minimum number of jumps: 3
How It Works
- Initialization: Create a steps array where steps[i] represents minimum jumps to reach index i.
- Base Case: steps[0] = 0 (no jumps needed to stay at start).
- Fill Array: For each position i, check all previous positions j that can reach i.
- Update: If position j can reach i and j is reachable, update steps[i] with minimum value.
Key Points
- If the first element is 0, it's impossible to move forward.
- Use INT_MAX to represent unreachable positions.
- The algorithm ensures we find the optimal solution through dynamic programming.
Conclusion
The dynamic programming approach efficiently solves the minimum jumps problem by building up solutions from smaller subproblems. It guarantees the optimal solution with O(n²) time complexity.
