45 Jump Game II
Last updated
Last updated
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.
For example:
Given array A =[2,3,1,1,4]
The minimum number of jumps to reach the last index is2
. (Jump1
step from index 0 to 1, then3
steps to the last index.)
Note: You can assume that you can always reach the last index.
Approach 1: Brute Force
Like with standard brute force procedures, we build a tree carries all possibilities, and recur on those. Consider the example above when A =[2,3,1,1,4]
. Beginning at index 0
, we can jump 2
places [1,3]
, from 1
, we can jump to [1]
, and from 3
, [4,1,1]
. Because we all explore all possible jump paths, the first time a BFS procedure identifies that a jump took it to the end of the array, the function immediately returns; as this is the shortest path. Both time and space complexity are exponential.
Approach 2: Greedy BFS
The solution to a linear time complexity deals with knowing which path to take in the brute force procedure discussed earlier. Let's think about it. Beginning at index 0
, we have [0:nums[0]]
options to chose from. Which option ensures to be the most optimal? Well, if we take the maximum element, we know we can reach further out in the array. Potentially, it could exceed the size of the array, but that does not matter, because we can simply chose the end. This however, is not optimal. Consider the counter example of a decreasing vector. The algorithm would always select the next element, and only ever move 1 step closer to the end of the array. However, if we consider the index in addition to the element, we ensure that we optimally close to the end of the array. This is because moving an additional index forward is the same as if the previous element took you that same distance. Both the element and the index carry distance in the sense of begin being able to either jump further, or physically get further.
Some Testing