Jump Game II Problem: 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.
Example :
Input: nums = [2,3,1,1,4] Output: 2 Explanation: 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.
Table of Contents
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;
}