DEV Community

Rakesh Reddy Peddamallu
Rakesh Reddy Peddamallu

Posted on

Leetcode - 45. Jump Game II

The question says that we can be always able to reach the end , only that we need to find is the min steps we can take.

We need 0 jumps to be at index 0 since we are starting there

Image description

Now from 2 we can jump to either jump to 3 or 1
Image description

we can represent this window by l , r pointers
Image description

now the next jump window is from 1 to 4 ( since this is the point they can jump max from window [3,1]
Image description

CODE:

/**
 * @param {number[]} nums
 * @return {number}
 */
var jump = function(nums) {
    let result = 0 ;
    let l = 0 ;
    let r = 0;
    while(r<nums.length-1){

        let farthest = 0 ;
        for(let i=l;i<=r;i++){
            farthest = Math.max(farthest , i+ nums[i]);
        }
        l = r + 1 ;
        r = farthest;
        result++;
    }
    return result
};
Enter fullscreen mode Exit fullscreen mode

Please go through the video by neetcode if you do not understand

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs