[Programming Problem] Jump Game II

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.

Example 1:
Input: nums = [2,3,1,1,4]
Output: 2
Explanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index.

Example 2:
Input: nums = [2,3,0,1,4]
Output: 2

[Programming Problem]

At every step jump and update values (if smaller) in the landing step. Let’s take the example of [2, 3, 1, 1, 4]. We start by initializing the ret array with MAX_VALUE’s. Then for position 0, we update position 1 and 2 with updated minimum value of 1. We keep doing this for the full array.

[2, 3, 1, 1, 4]
 
Initialize           -> [ 0, 1.797e+308, 1.797e+308, 1.797e+308, 1.797e+308 ]
Jump from position 0 -> [ 0, 1, 1, 1.797e+308, 1.797e+308 ]
Jump from position 1 -> [ 0, 1, 1, 2, 2 ]
Jump from position 2 -> [ 0, 1, 1, 2, 2 ]
Jump from position 3 -> [ 0, 1, 1, 2, 2 ]
Jump from position 4 -> [ 0, 1, 1, 2, 2 ]
[3, 0, 0, 1, 4]
 
Initialize           -> [ 0, 1.797e+308, 1.797e+308, 1.797e+308, 1.797e+308 ]
Jump from position 0 -> [ 0, 1, 1, 1, 1.797e+308 ]
Jump from position 1 -> [ 0, 1, 1, 1, 1.797e+308 ]
Jump from position 2 -> [ 0, 1, 1, 1, 1.797e+308 ]
Jump from position 3 -> [ 0, 1, 1, 1, 2 ]
Jump from position 4 -> [ 0, 1, 1, 1, 2 ]
/**
 * @param {number[]} nums
 * @return {number}
 */
var jump = function(nums) {
    const ret = [0].concat(new Array(nums.length-1).fill(Number.MAX_VALUE));
    for (let i = 0 ; i < nums.length ; i++ ) {
        let currStep = nums[i];
        //console.log(i, currStep)
        for (let jump = 1 ; jump <= currStep ; jump++) {
            //console.log("jump", jump, i + jump)
            if ( ret[i + jump] > ret[i] + 1 ) {
                ret[i + jump] = ret[i] + 1
            }
        }
    }
    //console.log(ret)
    return ret[nums.length-1]
};

Leave a Reply

Your email address will not be published. Required fields are marked *