Java Solution easy to understand


  • 89
    X
    public boolean canJump(int[] A) {
        int max = 0;
        for(int i=0;i<A.length;i++){
            if(i>max) {return false;}
            max = Math.max(A[i]+i,max);
        }
        return true;
    }

  • 5
    H

    Python version, can stop iteration early

    class Solution:
        # @param A, a list of integers
        # @return a boolean
        def canJump(self, A):
            maxs=0
            for idx,item in enumerate(A):
                if maxs<idx:
                    return False
                maxs=max(maxs,idx+item)
                if maxs>=len(A)-1:
                    return True

  • 1
    S

    The loop will stop when max cannot reach cur or max can reach the last index.

    public class Solution {
        public boolean canJump(int[] nums) {
            int max = 0, length = nums.length;
            for(int cur = 0; cur <= max && max < length - 1; max = Math.max(cur + nums[cur], max), cur++);
            return max >= length - 1;
        }
    }

  • 0
    S
    This post is deleted!

  • 0
    R

    @xniu said in Java Solution easy to understand:

    public boolean canJump(int[] A) {
    int max = 0;
    for(int i=0;i<A.length;i++){
    if(i>max) {return false;}
    max = Math.max(A[i]+i,max);
    }
    return true;
    }

    Get it,Thanks. the "max" mean the farthest distance that can be reached currently,right?


  • 0
    X

    No, your answer is TLE. However, I think it is LeetCode's error


  • 0
    C

    I don't think that solution works. I'm not sure if the problem definition changed, but I made a modification and it works fine.

    public static bool CanJump(int[] nums)
    {
                int max = 0;
    
                for (int i = 0; i < nums.Length;i++){
                    if (i > max) return false;
                    max = Math.Max(nums[i]+i, max); 
                }
                return true; 
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.