# 45. Jump Game II (Hard)

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

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.

Your goal is to reach the last index in the minimum number of jumps.

Example:

```Input: [2,3,1,1,4]
Output: 2
Explanation: The minimum number of jumps to reach the last index is 2.
Jump 1 step from index 0 to 1, then 3 steps to the last index.```

Note:

You can assume that you can always reach the last index.

## Solutions

``````class Solution {
public int jump(int[] nums) {
if (nums == null) {
return -1;
}

int len = nums.length;
if (len == 1) {
return 0;
}

int[] hops = new int[len];

// use Integer.MAX_VALUE in case of overflow issue
Arrays.fill(hops, Integer.MAX_VALUE / 2);

hops[len - 1] = 0;

// Scan from the tail to the head and keep the possibility for each slot whether
// it is able to reach the last index or not
for (int i = len - 2; i >= 0; i--) {

int min = Integer.MAX_VALUE / 2;

// j can move within the range [i, i + nums[i]]
// j cannot overstep the boundary of give array

for (int j = i; j < len && j <= i + nums[i]; j++) {

// if j can reach the last index, i can walk through j to reach the last index.

min = Math.min(min, hops[j] + 1);
}

hops[i] = min;
}

return hops;
}
}
``````