GAZAR

Principal Engineer | Mentor

Jump Game Algorithm

Jump Game Algorithm

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.

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.
const canJump = function(nums) {    
    if (nums.length <= 1){
        return true;
    }

    let maximum = nums[0]
    for (let i = 0; i < nums.length; i++) {
        if (maximum <= i && nums[i] === 0) {
            return false;
        }

        if (i+nums[i] > maximum){
            maximum = i + nums[i]
        }

        if (maximum >= nums.length - 1) {
            return true;
        }
    }
    return false
};