
Sponsored
Sponsored
The greedy approach involves making a jump only when absolutely necessary. Track the maximum index you can reach at each step and make a decision to jump when you get to the maximum of the current window. This ensures the least number of jumps.
Time Complexity: O(n), where n is the number of elements in the array, because we make a single pass through the array.
Space Complexity: O(1), since we are using a fixed amount of extra space.
1#include <stdio.h>
2
3int jump(int* nums, int numsSize) {
4 int jumps = 0, currentEnd = 0, farthest = 0;
5 for (int i = 0; i < numsSize - 1; i++) {
6 farthest = (farthest > i + nums[i]) ? farthest : i + nums[i];
7 if (i == currentEnd) {
8 jumps++;
9 currentEnd = farthest;
10 }
11 }
12 return jumps;
13}
14
15int main() {
16 int nums[] = {2, 3, 1, 1, 4};
17 int length = sizeof(nums) / sizeof(nums[0]);
18 printf("Minimum jumps: %d\n", jump(nums, length));
19 return 0;
20}We maintain two variables: `farthest`, which tracks the farthest point reachable, and `currentEnd`, which tracks the end of the current jumping range. A jump is made when we reach `currentEnd`, which updates to `farthest`.
The dynamic programming approach calculates the minimum jumps required to reach each index. For each index, calculate the minimum number of jumps required from all previous indices that can reach the current index. However, this approach is less efficient in terms of time complexity.
Time Complexity: O(n^2), where n is the number of elements.
Space Complexity: O(n), due to the use of a DP array.
1#
Use an array `dp` to store the minimum number of jumps to reach each index. Initialize `dp[0]` with zero since no jumps are needed to reach it.