DEV Community

Prashant Mishra
Prashant Mishra

Posted on • Originally published at leetcode.com

Jump game II leetcode problem

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.

Solution : Using Memoization dp (top-down approach)

class Solution {
    public int jump(int[] nums) {
        if(nums.length==1)return 0;
        int dp[] =new int[nums.length];
        Arrays.fill(dp,10001); // since max length is of 10^4 , hence max jump can't exceed 10^4
        return solve(nums,0,dp);
    }
    int solve(int[] nums,int index, int dp[]){
        //base cases
        if(index==nums.length-1) return 0;
        if(index>=nums.length)return 10001;
        if(dp[index]!=10001) return dp[index];
        //since we are allowed to move i+1,i+2,....i+k give i+k <=i+nums[i]
        for(int i = index+1;i<=index+nums[index] ;i++){
                dp[index] = Integer.min(dp[index],1+solve(nums,i,dp));
            // since every jump that we will make from current index 'index', hence min distance will be distance from current index 'index' to the last index;
        }
        return dp[index];
    }
}
Enter fullscreen mode Exit fullscreen mode

Latest comments (0)