Jump Game II - Golang
Problem statement:
You are given an integer array nums. You are initially positioned at the array’s first index, and each element in the array represents your maximum jump length at that position.
Return the minimum number of jumps to reach nums[n - 1]. The test cases are generated such that you can reach nums[n - 1].
Example:
Input:
[2,3,1,1,4]
Expected output:
2
If you would like to solve the problem on Leetcode, here is the link to the problem: https://leetcode.com/problems/jump-game-ii
Golang Solution:
func jump(nums []int) int {
if len(nums) == 1 {
return 0
}
res := 0
i := len(nums)-1
for i >= 0 {
j := i
currPos := i
for j >= 0 {
if j + nums[j] >= i {
currPos = j
}
j -= 1
}
if currPos != i {
res += 1
}
if currPos == 0 {
break
}
i = currPos
}
return res
}