
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.
1public class Solution {
2 public int Jump(int[] nums) {
3 int jumps = 0, currentEnd = 0, farthest = 0;
4 for (int i = 0; i < nums.Length - 1; i++) {
5 farthest = Math.Max(farthest, i + nums[i]);
6 if (i == currentEnd) {
7 jumps++;
8 currentEnd = farthest;
9 }
10 }
11 return jumps;
12 }
13
14 static void Main(string[] args) {
15 Solution sol = new Solution();
16 int[] nums = {2, 3, 1, 1, 4};
17 Console.WriteLine("Minimum jumps: " + sol.Jump(nums));
18 }
19}Implement the logic within a loop, determining when to jump by checking when the loop index equals the `currentEnd`. Update `farthest` for each index and adjust the number of jumps accordingly.
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#include <iostream>
#include <vector>
#include <limits.h>
using namespace std;
int jump(vector<int>& nums) {
vector<int> dp(nums.size(), INT_MAX);
dp[0] = 0;
for (int i = 1; i < nums.size(); ++i) {
for (int j = 0; j < i; ++j) {
if (j + nums[j] >= i) {
dp[i] = min(dp[i], dp[j] + 1);
}
}
}
return dp[nums.size() - 1];
}
int main() {
vector<int> nums = {2, 3, 1, 1, 4};
cout << "Minimum jumps: " << jump(nums) << endl;
return 0;
}Use a dynamic table `dp` where `dp[i]` is the fewest number of jumps required to reach index `i`. Iterate over each index and possible previous jumps to determine the smallest number of jumps.