You are given an integer array nums
. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position.
Return true
if you can reach the last index, or false
otherwise.
Example 1:
Input: nums = [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
Example 2:
Input: nums = [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.
Constraints:
1 <= nums.length <= 104
0 <= nums[i] <= 105
The task is to determine if we can jump to the last index starting from the first index. We can solve this optimally by working backward.
The idea is to use a "goal" that starts at the last index and moves backward whenever a preceding index can reach or surpass it. If we can move the goal to the first index, the last index is reachable.
The idea is to use a "goal" that starts at the last index and moves backward whenever a preceding index can reach or surpass it. If we can move the goal to the first index, the last index is reachable.
Input: nums = [2,3,1,1,4]
[2,3,1,1,4]
i g
i = current position
g = goal
current position + maximum jump >= goal
= 3 + 1 >= 4
= true
[2,3,1,1,4]
i g
current position + maximum jump >= goal
= 2 + 1 >= 3
= true
[2,3,1,1,4]
i g
current position + maximum jump >= goal
= 1 + 3 >= 2
= true
[2,3,1,1,4]
i g
current position + maximum jump >= goal
= 0 + 2 >= 1
= true
[2,3,1,1,4]
g
if goal == 0
class Solution {
public:
bool canJump(vector<int>& nums) {
int goal = nums.size() - 1;
std::cout << nums.size() - 2 << std::endl;
for (int i = nums.size() - 2; i >= 0; i-- )
{
if (i + nums[i] >= goal) {
std::cout << "\n" << i << " " << goal << std::endl;
goal = i;
}
std::cout << i << " " << goal << std::endl;
}
return goal == 0;
}
};
Why we can't do it from the left index 0?
If we start it from the left index, then we need to move the index to the next successive goal everytime. In this case, we need to add more conditions to check if not greater than the last index.
Comments
Post a Comment