Start with an array A of positive numbers. Start at index 0. From index i, you can move to index i+x for any x <= A[i]. The goal is to find the minimum number of moves needed to get to the end of the array.
Here's an example:
{ 2 , 4 , 1 , 2 , 3 , 2 , 4 , 2}
If you always go as far as possible in each move, then this is what you get:
0 , 2 , 3 , 5 , 7
This takes 4 moves. But you can get through it faster by doing it this way
0 , 1 , 4 , 7
This only takes 3 moves.
I thought about this for a bit and did the first thing I thought of, but after thinking for a few more days, I still don't know how to do it any better.
Here's my idea. Start at the end of the array and keep track of the minimum number of moves from some position to the end. So for the example, moves[7] = 0
because it's the end already. Then moves[6] = 1
because it takes one move to get to the end. My formula is
moves[i] = 1 + min(moves[i+1], moves[i+2], ... , moves[i+A[i]])
By the time I get to the beginning, I know the number of moves.
So this is O(n^2) which is okay I guess, but probably there is a faster way?