DEV Community

Prashant Mishra
Prashant Mishra

Posted on • Edited on • Originally published at leetcode.com

Jump game leetcode problem

Problem
You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position.

Return true if you can reach the last index, or false otherwise.

Example 1:

Input: nums = [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.

Solution: Dp memoization (top down approach)

class Solution {
    public boolean canJump(int[] nums) {
        int dp[] = new int[nums.length];
        Arrays.fill(dp,-1);//intialize with -1 for univisted index
        return jumpToEnd(0,nums,dp);
    }
    public boolean jumpToEnd(int index, int [] nums,int dp[]){
    //base case
        if(index>= nums.length-1) return true;// if we are able to reach to last index or go beyond
        if(dp[index]!=-1) return dp[index]==1;// if this index has already been explored then simple return the result
        for(int jump = 1;jump<=nums[index];jump++){//we can jump atleat 1 step/index ( given nums[index]>=1) and atmost nums[index] steps/indexes
            if(jumpToEnd(index+jump,nums,dp)) {//going to index+jump = newindex, if the newindex is last index or beyond then return true;
                dp[index] = 1;
                return true;
            }
        }
        dp[index] =0;
        return false;//otherwise we are not able to reach to last index even after trying all the steps
    }
}

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.