Tags: LeetCode DSA Greedy Algorithms
Prompt:
You are given an array of integers nums, where nums[i] represents the maximum length of a jump towards the right from index i. For example, if you are at nums[i], you can jump to any index i + j where:
j <= nums[i]i + j < nums.length
You are initially positioned at nums[0].
Return the minimum number of jumps to reach the last position in the array (index nums.length - 1). You may assume there is always a valid answer.
Example 1:
Input: nums = [2,4,1,1,1,1]
Output: 2Explanation: Jump from index 0 to index 1, then jump from index 1 to the last index.
Example 2:
Input: nums = [2,1,2,1,0]
Output: 2Constraints:
1 <= nums.length <= 10000 <= nums[i] <= 100
Solution:
class Solution {
public:
int jump(vector<int>& nums)
{
if(nums.size() == 0 || nums.size() == 1) {return 0;}
int farthest = 0;
int currentEnd = 0;
int counter = 0;
for(int i = 0; i < nums.size()-1; i++)
{
//farthest reachable position
farthest = max(farthest, nums[i] + i);
//current range calculation
if(currentEnd == i)
{
counter++;
currentEnd = farthest;
if (currentEnd >= nums.size() - 1) return counter;
}
}
return counter;
}
};
Explanation:
So this one I still do not outright get, I mean basically it is kind of like the jump game original, where you basically just check each value to see if you have a new furthest, and that idea gets you really far in this one, but the main real difference now is the range.
You can have a case where the range holds the same value as the largest int but its just further down the range so if you check farthest it updates that range every single time, which is why you need to keep track of how far you can go from where you can reach right now, but as soon as you get out of that range, you know you had to have made a jump, so you need to increment that counter variable.
We then set ourselves to the new farthest range that we found in that entire scan of the original range, so you basically just make a guess and then you see whats the best thing you can find as you keep on moving forward, and then you update it when you get past it, a bit strange but it is still a greedy algorithm if you really think about it, O(n) time and O(1) space