55. Jump Game #
Problem #
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.
Problem Summary #
Given an array of non-negative integers, you are initially positioned at the first position of the array. Each element in the array represents the maximum jump length at that position. Determine whether you can reach the last position.
Solution Approach #
- Given a non-negative array, determine whether you can reach the last position of the array starting from index 0.
- This problem is relatively simple. If a certain cell as a
starting pointcan jump a distance ofn, then it means the nextncells can all serve asstarting points. For every cell that can serve as astarting point, try jumping once and continuously update thefarthest distance maxJumpthat can be reached. If you can keep jumping to the end, then it succeeds. If at some point the current index is greater thanmaxJump, it means the segment between this point and maxJump is disconnected, and some points cannot reach the last position.
Code #
func canJump(nums []int) bool {
n := len(nums)
if n == 0 {
return false
}
if n == 1 {
return true
}
maxJump := 0
for i, v := range nums {
if i > maxJump {
return false
}
maxJump = max(maxJump, i+v)
}
return true
}