Sunday, May 27, 2012

Jump Game (2)

[Question]
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]
Be greedy. Assume the minimum steps to reach position i is S[i], then from position i+1 to A[i]+i, the steps to reach are at most S[i]+1 (part of [ i+1, A[i]+i ] may already be reached before using A[i]).

[Solution]
//-----------
//-- C++ --
//-----------
class Solution {
public:
    int jump(vector<int>& nums) {
        int n=nums.size();
        vector<int> cnt(n,0);

        for (int i=0, k=0; i<n && k<n; i++)
            for(int j=k; j<min(n, nums[i]+i+1); j++,k++)
                cnt[j] = (i==j)?0:cnt[i]+1;
               
        return cnt.back();
    }
};

No comments:

Post a Comment