Tuesday, November 11, 2014

Jump Game II

//from anniekim
Solution: Jump to the position where we can jump farthest (index + A[index]) next time.

    int jump(int A[], int n) {
        int start = 0;
        int res = 0;
        while (start < n-1)
        {
            res++;//this means we will jump one step
            if (start + A[start] >= n-1)
                return res;
          //compute to which index we will jump
            int mx = start;
            for (int i = start + 1; i <= start + A[start]; ++i)
                if (i + A[i] >= mx + A[mx])
                    mx = i;
            start = mx;//here the jump is done.
        }
    }

No comments:

Post a Comment