Jump Game II
Problem Statement
Given an array of non-negative integer 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 1:
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.
Approach 1:- BFS
Can be thought of as a BFS Problem. Where the nodes in the ith level are all the nodes that can be reached from the i-1th level.
2
3 1
1 4
Clearly, 4 can be reached by only 2 jumps.
class Solution {
public:
int jump(vector<int>& nums) {
if(nums.size()<=1) return 0;
int cur_max=0,i=0;
int level=0;
while(i<=cur_max)
{
int at_max=cur_max;
for(;i<=cur_max;i++)
{
at_max=max(at_max,nums[i]+i);
if(at_max>=nums.size()-1) return level+1;
}
cur_max=at_max;
level++;
}
return 0;
}
};
Time Complexity:- 0(N)
Space Complexity:- 0(1)
Approach 2:- We can start traveling from the back and for each index, we can check for reaching to that index how many jumps are needed.
#define MAX 100001
class Solution {
public:
int jump(vector<int>& nums) {
vector<int> dp(nums.size(),0);
for(int i=nums.size()-2;i>=0;i--)
{
int steps=nums[i]+i;
int ans=MAX;
for(int j=i+1;j<=steps&&j<nums.size();j++)
{
if(nums[j]==0) continue;
ans=min(ans,dp[j]);
}
if((nums[i]+i)>=(nums.size()-1)) ans=0;
dp[i]=++ans;
}
return dp[0];
}
};
Time Complexity:- 0(N*N)
Space Complexity:- 0(N)