55. Jump Game
Input: [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.Input: [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.// Greedy
bool canJump(vector<int>& nums) { // time: O(n); space: O(1)
int n = nums.size(), maxReach = 0;
for (int i = 0; i < n; ++i) {
if (i > maxReach || maxReach >= n - 1) break;
maxReach = max(maxReach, i + nums[i]);
}
return maxReach >= n - 1;
}Last updated