Thursday, January 29, 2015

Jump Game II LeetCode

Greedy

4 2 3 5 1 2 3 2 1 2

When we searching 4, the next step for us is calculating the largest coverage for "2 3 5 1".
Although the code is easy, it is not easy to get the clear solution for this kind of question.

The code is as follows:

public int jump(int[] A) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
       
        int steps = 0;
        int last = 0;
        int coverage = 0;
       
        for (int i=0; i<A.length; i++) {
            if (i > last) {
                steps++;
                last = coverage;
            }
            coverage = Math.max(coverage, A[i] + i);
        }
        return steps;
    }

No comments:

Post a Comment