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

Top comments (0)

Great read:

Is it Time to go Back to the Monolith?

History repeats itself. Everything old is new again and I’ve been around long enough to see ideas discarded, rediscovered and return triumphantly to overtake the fad. In recent years SQL has made a tremendous comeback from the dead. We love relational databases all over again. I think the Monolith will have its space odyssey moment again. Microservices and serverless are trends pushed by the cloud vendors, designed to sell us more cloud computing resources.

Microservices make very little sense financially for most use cases. Yes, they can ramp down. But when they scale up, they pay the costs in dividends. The increased observability costs alone line the pockets of the “big cloud” vendors.