Skip to content

Commit

Permalink
Create Jump Game II.cpp
Browse files Browse the repository at this point in the history
You are given a 0-indexed array of integers nums of length n. You are initially positioned at nums[0].

Each element nums[i] represents the maximum length of a forward jump from index i. In other words, if you are at nums[i], you can jump to any nums[i + j] where:

0 <= j <= nums[i] and
i + j < n
Return the minimum number of jumps to reach nums[n - 1]. The test cases are generated such that you can reach nums[n - 1].
  • Loading branch information
chandrachood932c authored Oct 31, 2022
1 parent dbd4685 commit 9f542b4
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions Jump Game II.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/*
You are given a 0-indexed array of integers nums of length n. You are initially positioned at nums[0].
Each element nums[i] represents the maximum length of a forward jump from index i. In other words, if you are at nums[i], you can jump to any nums[i + j] where:
0 <= j <= nums[i] and
i + j < n
Return the minimum number of jumps to reach nums[n - 1]. The test cases are generated such that you can reach nums[n - 1].
*/

class Solution {
public:
int jump(vector<int>& nums) {
int n=nums.size();
vector<int> dp(n,INT_MAX);
dp[0]=0;

for(int i=0;i<n;i++)
{
int step = nums[i];
for(int j=1;j<=step and i+j<n;j++)
{
dp[i+j]=min(dp[i+j], dp[i]+1);
}
}

return dp[n-1];
}
};

0 comments on commit 9f542b4

Please sign in to comment.