Find minimum number of jumps to reach the last index.
Input: nums=[2,3,1,1,4] → Output: 2
Input: nums=[2,3,0,1,4] → Output: 2
DP: dp[i] = minimum jumps to reach index i.
- dp[0]=0, rest Integer.MAX_VALUE
- For each i: for each reachable j from i: dp[j]=min(dp[j],dp[i]+1)
- Return dp[n-1]
public int jump(int[] nums) {
int n = nums.length;
int[] dp = new int[n];
Arrays.fill(dp, Integer.MAX_VALUE);
dp[0] = 0;
for (int i = 0; i < n; i++) {
if (dp[i] == Integer.MAX_VALUE) continue;
for (int j = 1; j <= nums[i] && i + j < n; j++)
dp[i + j] = Math.min(dp[i + j], dp[i] + 1);
}
return dp[n - 1];
}
- Time Complexity: O(n^2)
- Space Complexity: O(n)