LeetCode 45. Jump Game II (javascript solution)
codingpineapple
Posted on May 6, 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.
Your goal is to reach the last index in the minimum number of jumps.
You can assume that you can always reach the last index.
Solution:
Time Complexity : O(n)
Space Complexity: O(1)
// Greedy solution
var jump = function(nums) {
let newMax = 0;
let jump = 0;
let oldMax = 0;
for (let i=0;i<nums.length-1;i++) {
// Keep track of the farthest jump
newMax = Math.max(newMax, i+nums[i]);
// When we get to the index where we had our previous farthest jump, we increase our jump count by 1
if (i == oldMax) {
jump++;
oldMax = newMax;
}
}
return jump;
};
π πͺ π
π©
codingpineapple
Posted on May 6, 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