DEV Community

codingpineapple
codingpineapple

Posted on

LeetCode 55. Jump Game (javascript solution)

Description:

Given an array of non-negative integers nums, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Determine if you are able to reach the last index.

Solution:

Time Complexity : O(n)
Space Complexity: O(1)

var canJump = function(nums) {
    // Keep track of max distance traveled so far
    let max = 0;
    for(let i=0;i<nums.length;i++){
        // The only time that max < i is when we are at 0 and we cannot move forward
        if(i>max) return false;
        // Move the max pointer the maximum 
        max = Math.max(nums[i]+i,max);
    }
    // If we did not get stuck at a 0 then return true
    return true;
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)