Sunday, May 11, 2014

[LeetCode] Jump Game I && II

Jump Game I
Problem Statement (link):
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.
Determine if you are able to reach the last index.
For example:
A = [2,3,1,1,4], return true.
A = [3,2,1,0,4], return false.
Analysis:
Starting from the first entry, for each of the reachable next entries, we find the maximum reachable position. If the max reachable position is at end of array, return true; otherwise, return false.

Code:
class Solution {
public:
    bool canJump(int A[], int n) {
        int maxReach=0;

        for (int i=0; i<=maxReach && maxReach<=n-1; i++)
            maxReach=max(maxReach, A[i]+i);

        return maxReach>=n-1;
    }
};


Jump Game II
Problem Statement (link):
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:
We use the same methodology as that in the previous problem to find the farthest reachable position - maxReach - from index i. The idea is that we record the number of steps while we reach the farthest possible position from current index i. As long as we reach at or farther than the end of array, we found the solution.

E.g., A = [2, 3, 1, 1, 4, 1]
run 1: i = 0, found maxReach = 2 starting at index 0, number of steps = 1
run 2: i = 1, found maxReach = 4 starting at index 1, number of steps = 2
run 3: i = 4, found maxReach = 8 starting at index 4, number of steps = 3
--> found.

Again, the core of this algorithm is finding the farthest reachable position starting within the reachable range from previous index.

Code:
class Solution {
public:
    int jump(int A[], int n) {
        int maxReach=0, currFar=0, minStep=0;

        for (int i=0; i<n; ) {
            if (currFar>=n-1) break;

            while(i<=currFar) { // same as the for loop in previous problem
                maxReach=max(maxReach,A[i]+i);
                i++;
            }
            minStep++;
            currFar=maxReach;
        }
        return minStep;
    }
};

No comments:

Post a Comment