In this Leetcode Jump Game II problem solution, we have given Given an array of non-negative integers nums, 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. You can assume that you can always reach the last index.

Leetcode Jump Game II problem solution


Problem solution in Python.

class Solution(object):
def jump(self, nums):
    res = 0
    edge = 0
    maxEdge = 0
    for i in range(len(nums)):
        if i > edge:
            edge = maxEdge
            res += 1
        maxEdge = max(maxEdge,i+nums[i])
    return res



Problem solution in Java.

class Solution {
    public int jump(int[] nums) {
         int ladder = 0;
         int stair = 1;
         int jump = 0;
 
         for (int level = 0; level < nums.length; level++) {
             if (level == nums.length - 1) {
                 return jump;
             }
             if (nums[level] + level >= ladder)
                 ladder = nums[level] + level;
 
             stair--;
 
             if (stair == 0) {
                 jump++;
                 stair = ladder - level;
                 if (stair == 0)
                     return -1;
             }
         }
         return jump;
    }
}


Problem solution in C++.

class Solution {
public:
    int jump(vector<int>& nums) {
        int jumps = 0 , limit = 0 , next_limit = 0;
        for(int i = 0;i < nums.size()-1;i++){
            next_limit = max(next_limit,i+nums[i]);
            if(i == limit){
                jumps++;
                limit = next_limit;
            }
        }
        return jumps;
    }
};


Problem solution in C.

int jump(int* n, int ns){
    if(ns <= 1) return 0;
    int r = n[0];
    if(r >= ns - 1) return 1;
    int max = r + n[r];
    int maxid = r;
    for(int i = 1; i <= r; i++)
        if(n[i] + i > max)
            max = n[i] + i, maxid = i;
    return jump(&n[maxid], ns - maxid) + 1;
}