55. Jump Game

February 2019 1 minute read

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.


This greedy problem, we can use a variable most_far to track how far can we reach. If we found a bigger value, we can update the most_far variable. In the end, we should return if the most_far value is bigger than the length of the array.


Traverse array only once.

There is only one variable most_for.


class Solution:
    def canJump(self, nums: List[int]) -> bool:
        most_far = nums[0]
        i = 0
        while i < len(nums) and most_far >= i:
            if nums[i] + i > most_far:
                most_far = nums[i] + i
            i += 1
        return most_far >= len(nums) - 1
func canJump(nums []int) bool {
	mostFar := nums[0]
	for index := 1; index < len(nums)-1; index++ {
		if nums[index]+index > mostFar && mostFar >= index {
			mostFar = nums[index] + index
	return mostFar >= len(nums)-1