My code-
The prob-https://leetcode.com/problems/jump-game-ii/
Please correct the code and send it
hello @Somasree
your code will run in infinite loop (check ur while loop).
also the greedy logic that u r trying to implement is bit different so recheck ur logic.
int jump(vector<int>& nums) {
int n = nums.size();
// Base case when size < 2
if(n < 2) return 0;
// Initially we can reach max to nums[0]
int maxReachableIndex = nums[0];
// intially my limit is 0 + nums[0];
int limit = nums[0];
// Make one jump from 0
int minJumps = 1;
// Check from 1 to n-1
for(int i=1; i<n; i++){
// If we reach the current limit i.e i + nums[i], so we need to change out new limit and take next jump
if(i > limit){
minJumps++;
limit = maxReachableIndex;
}
// if my i is not greater than current limit than we need to update our maxReachableIndex to i+nums[i] i.e from i we can reach to max of i+nums[i]
maxReachableIndex = max(maxReachableIndex, i + nums[i]);
}
return minJumps;
}
Why do we initialize max reachable index or limit to 0
we have initialised it with nums[0] becuase from index 0 we can reach atmax nums[0] distance.
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.