Prompt:

You are given an integer array nums where each element nums[i] indicates your maximum jump length at that position.

Return true if you can reach the last index starting from index 0, or false otherwise.

Example 1:

Input: nums = [1,2,0,1,0]
 
Output: true

Explanation: First jump from index 0 to 1, then from index 1 to 3, and lastly from index 3 to 4.

Example 2:

Input: nums = [1,2,1,0,1]
 
Output: false

Constraints:

  • 1 <= nums.length <= 1000
  • 0 <= nums[i] <= 1000

Solution:

class Solution {
public:
    bool canJump(vector<int>& nums) 
    {
        int farthest = 0;
        for(int i = 0; i < nums.size(); i++)
        {
            if(i > farthest)
            {
                return false;
            }
            farthest = max(farthest, nums[i] + i);
            
            //std::cout << "Farthest: " << farthest << std::endl;
            if(farthest >= nums.size()-1) {return true;}
        }
 
        return false;
    }
};
 

Explanation:

So this one was a little bit weird, at first I thought you could only jump the given amount that they give you, but turns out you can actually jump less or exactly that amount. So the solution here is to look at the given furthest jump that you actually can make, and then not give a fuck about making it.

So for each of the given indexes you loop over them and then add this current index plus the value at that index to see how far you can jump. The only real issue of course becomes whenever you reach an index that is greater than your furthest jump, because you would not have been able to make it there given the rules, so if that happens you return false outright.

If the index is ever farther than the size of the array, then you know you are all good, and if the loop ever ends without the index becoming greater than the furthest point you could reach then you are all good as well.