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

https://leetcode.com/problems/jump-game-ii/

Solution: Greedy

public class Solution {
    public int jump(int[] nums) {
        if (nums.length <= 1) {
            return 0;
        }    

        int i = 0, jump = 0;

        while (i < nums.length) {
            int max = -1;
            if (nums[i] == 0 && i < nums.length-1) {
                return -1;
            }
            if (i >= nums.length-1) {
                return jump;
            }

            jump++;

            if (i+nums[i] >= nums.length-1) {
                return jump;
            }

            int t = i; // this line is important
            for (int j = 1; j <= nums[t]; j++) {
                int k = t+j;
                if (k < nums.length && k + nums[k] > max) {
                    max = k+ nums[k];
                    i = k;
                }
            }
        }
        return -1;
    }
}

Note: why line "int t == i;" is necessary ??

Solution II:

public class Solution {

    public int jump(int[] A) {
        int jumps = 0, curEnd = 0, curFarthest = 0;
        for (int i = 0; i < A.length - 1; i++) {
            curFarthest = Math.max(curFarthest, i + A[i]);
            if (i == curEnd) {
                jumps++;
                curEnd = curFarthest;

                if (curEnd >= A.length - 1) {
                    break;
                }
            }
        }
        return jumps;
    }
}

https://leetcode.com/discuss/67047/concise-o-n-one-loop-java-solution-based-on-greedy