Jump Game II

[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.

For example:
Given array A = [2,3,1,1,4]

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.)

[Analysis]

A naive approach is to use DP and without checking if (i+A[i] > farthest) before running the for loop to check if we’ve found a shorter path. In fact, if this condition is not satisfied, we can never have a shorter path since we can only arrive in positions previously covered in less steps. Only when starting at a position, we are expanding our reachable area, is it possible to update our miniSteps.

Also, we will only update starting from farthest, for the same reason. This brings the total complexity to O(n).

    int jump(int A[], int n) {
        vector<int> miniSteps(n, INT_MAX);
        miniSteps[0] = 0;
        int farthest = 0;

        for (int i=0; i<n; ++i){
            if (i <= farthest) {
                // otherwise at position i, we won't be able to expand our atteinable area
                // thus we are only wasting one more step to get to where we can already reach before.
                if (i+A[i] > farthest) {
                    // we can possibly extend our atteinable land!
                    for (int j=farthest; j<n && j<=i+A[i]; ++j) {
                        if (miniSteps[i] + 1 < miniSteps[j])
                            miniSteps[j] = miniSteps[i]+1;
                    }
                    farthest = i+A[i];
                }
            } else {
                // i > farthest already, destination not atteinable
                break;
            }
        }
        if (miniSteps[n-1] != INT_MAX)
            return miniSteps[n-1];
        return -1;
    }