sourcecode

Saturday, December 1, 2012

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.)
/**For example {4,1,1,3,1,1,1}.
Step 1: Start with 4 (index=0), get the furthest range (index=[1,4]).
Step 2: Within the range (index=[1,4]), the furthest one can get using one of the elements in the range, is using 3 (index=3), and the new range is (index=[5,6]). The new range reaches the lastIndex. Done
*/
class Solution {
private:
    int getMaxRangeIndex(int A[], int start, int end){
        int index = start;
        int maxRange = start+A[start];
        for(;start<=end; ++start){
            if (start+A[start] > maxRange){
                index = start;
                maxRange = start+ A[start];
            }
        }
        return index;
    }
public:
    int jump(int A[], int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (n <= 1) return 0;
        int const lastIndex = n-1;
        int steps = 0;
        int lowBound = 0;
        int highBound = 0;
        while(highBound < lastIndex){
            int ii = getMaxRangeIndex(A,lowBound, highBound);
            ++steps;
            lowBound = highBound+1;
            highBound = ii + A[ii];
        }
        return steps;
    }
};

No comments: