DEV Community

Prashant Mishra
Prashant Mishra

Posted on • Updated 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)