You are given a 0-indexed array of integers nums of length n. Initially, you are positioned at the first index of the array.
Each element nums[i] represents the maximum length of a forward jump from index i.
Your goal is to reach the last index in the minimum number of jumps.
You can assume that you can always reach the last index.
Input: nums = [2, 3, 1, 1, 4]
Output: 2
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
Input: nums = [2, 3, 0, 1, 4]
Output: 2
1 <= nums.length <= 10^40 <= nums[i] <= 10000 since you’re already at the last index.To solve this problem, we will use a greedy approach:
currentEnd variable to represent the end of the range for the current jump.farthest index that can be reached.currentEnd, increment the jump count and update currentEnd to farthest.Here is the C++ implementation:
#include <vector>
#include <iostream>
#include <algorithm>
int jump(std::vector<int>& nums) {
int n = nums.size();
if (n <= 1) return 0;
int jumps = 0, currentEnd = 0, farthest = 0;
for (int i = 0; i < n - 1; ++i) {
farthest = std::max(farthest, i + nums[i]);
if (i == currentEnd) {
jumps++;
currentEnd = farthest;
if (currentEnd >= n - 1) {
break;
}
}
}
return jumps;
}
// Example usage
int main() {
std::vector<int> nums = {2, 3, 1, 1, 4};
std::cout << "Minimum number of jumps: " << jump(nums) << std::endl; // Output: 2
return 0;
}
O(n) where n is the length of the array. We only make a single pass through the array.O(1) as we use a constant amount of additional space.This implementation ensures that we find the minimum number of jumps required to reach the last index in an efficient manner.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?