DevPath

← All problems

Jump Game

Medium greedy · arrays

Description

Each value is the maximum jump length from that position. Return true if you can reach the last index starting at index 0.

Constraints

1 <= n <= 100000; 0 <= nums[i]

Examples

Input: nums = [2,3,1,1,4]

Output: true

Input: nums = [3,2,1,0,4]

Output: false

Hints (1)
  • Track the furthest index reachable so far.

Solutions

Greedy furthest reach. · Time O(n) · Space O(1)

func canJump(nums []int) bool {
    reach := 0
    for i, n := range nums {
        if i > reach {
            return false
        }
        if i+n > reach {
            reach = i + n
        }
    }
    return true
}

Create a free account to submit solutions, track progress and save problems.

Create account