LeetCode 55. Jump Game (javascript solution)
codingpineapple
Posted on June 11, 2021
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;
};
π πͺ π
π©
codingpineapple
Posted on June 11, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
sorting Recap the highlight of the sorting algorithms using JavaScript for beginners
October 5, 2024
datastructures DSA with JS: Understanding Custom Array Data Structure in JavaScript - A Step-by-Step Guide
September 29, 2024