Saturday, May 26, 2012

Jump Game (1)

[Question]
Assume an array of integers, A[i]>=0, represents the maximum steps allowed to move forward from i. Starting scan from A[0], is there a path to reach the end of A (i.e. A[n-1])?

For example, given {3, 0, 2, 1, 2, 0, 0}, there is a path A[0], A[3], A[4], A[6]; given {3, 0, 2, 0, 2, 0, 0}, the path has to be A[0], A[2], A[4], A[6]; given {3, 1, 1, 0, 2, 0, 0},  no path to the end.

[Analysis]
Be greedy. Push the reach from the A[0] to forward index  j ="A[0]+0", A[1] to index j = max(j, A[1]+1), until i> j (unreachable anymore), or forward index j covers A's last index.

[Solution]
class Solution {
public:
    bool canJump(vector<int>& nums) {
        int i=0, j=0;
        while (i<=j) {
            j = max(j, nums[i]+i);
            if (j>=nums.size()-1)
                return true;
            i++;
        }
        return false;
    }
};

No comments:

Post a Comment