Leetcode- jumping game

Jumping game
 
 

Given a non negative integer array, you are initially located in the first position of the array.

Each element in the array represents the maximum length you can jump at that location.

Determine whether you can reach the last position.

Example 1:

Input: [2,3,1,1,4]Output: trueExplanation: jump 1 steps from position 0 to 1, then jump 3 steps to the last position.

Example 2: input: [3,2,1,0,4]

Output: falseExplanation: anyway, you always get to the index 3. But the maximum jump length is 0, so you can never get to the last position.

Train of thought: adoptdynamic programming。 According to the routine of dynamic programming, we first set up an array of DP.
dpRepresents the maximum length that the current position can jump to, so the DP must be greater than or equal to the length of the array - 1.
The equation of state is:dp[i]=Math.max(dp[i-1],nums[i]+i)(dp[i-1]>=i) else dp=0;
The explanation is as follows: the maximum length of the current jump is either the maximum length of the previous jump, if I can do this position,
Then the length that dp[i] can reach can be I+nums[i] or the maximum length before.
The condition of judgment is: DP [i-1] & gt; = i, which is to judge whether the maximum length can reach the current position, if not,
It shows that he will never be able to get to the next position, that is, the situation of nums[i]=0.
The code is as follows:
class Solution {
    public boolean canJump(int[] nums) {
      int len=nums.length;
        if(len==1)return true;
        //dpRepresents the maximum length that can jump.
        int dp[]=new int[len];
        dp[0]=nums[0];
        for(int i=1;i<len;i++){
            if(dp[i-1]>=i){
                dp[i]=Math.max(dp[i-1],nums[i]+i);
            }else {
                dp[i]=0;
            }
            
        }
       return dp[len-1]>=len-1;     
        
    
    }
}


A simpler approach is not to maintain an array, but to represent the maximum length that can be traversed directly with a variable.
public class Solution {
    public boolean canJump(int[] A) {

        int curmax=A[0];
        for(int i=0;i<A.length;i++){
                    if(curmax>=A.length-1)return true;
if(curmax>=i){
                curmax=Math.max(curmax,A[i]+i);
            }else {
                return false;
            }
            
        }
        return curmax>=A.length-1;
    }
}

 

 

Leave a Reply

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