Python Solution that easy to read with explanation

  • 1

    So the basic logic is |If I can reach end from this point|
    we set a range_ , which hold the value of the range we currently able to reach

    if this range_ if greater than the index of last elemnt len(ls)-1 then we can just return true

    if the range_ can not reach the end , we go from current index to index+1
    range_ = max(range_ , index + ls[index])
    this will give the new range if the new index's value can reach longer distance
    if index > range_ , this just means range_ is not long enough

    class Solution(object):
        def canJump(self, nums):
            :type nums: List[int]
            :rtype: bool
            # hold the range it can reach
            range_ = 0
            # for each elemnt in the ls
            for i in range(len(nums)):
                # if the range_ is unable to reach current index
                if range_ <i:
                    return False
                # get a longer range_ everytime gets to a new point
                range_ = max(range_ , i + nums[i])
                # if the new range is long enough
                if range_ >= len(nums) - 1:
                    return True
            return False

Log in to reply

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