Jump Game II

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.)

This problem can be solved using the greedy algorithm. The idea of the greedy algorithm is to find the best solution for current situation, and when all the best solutions of the local situation is calculated, we can combine the result and find the best situation.

Analysis:

We can scan through the whole array, increase step by step, keep track of the current reach, before reaching the reach, record the furthest reach in tmp. After reach the reach, extend the reach to the new tmp. Start the tmp again and increase the step by 1. When reach exceed the length, we can return the step

public class Solution {
    public int jump(int[] A) {
        if (A.length == 0)
            return 0;
        int steps = 0;
        int reach = 0;
        int tmp = reach;
        for (int i = 0; i < A.length; i++) {
            if (i > reach) {
                steps++;
                reach = tmp;
            }
            tmp = Math.max(A[i] + i, tmp);
            if (reach >= A.length-1)
                return steps;
        }
        return steps;
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s