Skip to content
Permalink
master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time

Given an array of non-negative integers, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Determine if you are able to reach the last index.

Example 1:

Input: [2,3,1,1,4] Output: true

Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.

Example 2:

Input: [3,2,1,0,4] Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.

My code:

class Solution:
    def canJump(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        #Greedy idea
        if len(nums)<=1:
            return True
        start=0
        far=0
        next_far=0
        while True:
            while start<=far:
                next_far=max([next_far,nums[start]+start])
                if next_far>=len(nums)-1:
                    return True
                start+=1
            
            if far==next_far and far<len(nums)-1:
                return False
            far=next_far

Solution: https://leetcode.com/problems/jump-game/