2770. Maximum Number of Jumps to Reach the Last Index
</> Solution
/**
* Problem: LeetCode 2770 - Maximum Number of Jumps to Reach the Last Index
* Difficulty: Medium
* Language: Java
* Author: CodeByTushu
*/
import java.util.Arrays;
class Solution {
public int maximumJumps(int[] nums, int target) {
int n = nums.length;
int[] dp = new int[n];
Arrays.fill(dp, -1);
dp[0] = 0;
for (int i = 1; i < n; i++) {
for (int j = 0; j < i; j++) {
if (dp[j] != -1) {
long diff = (long) nums[i] - nums[j];
if (diff >= -target && diff <= target) {
dp[i] = Math.max(dp[i], dp[j] + 1);
}
}
}
}
return dp[n - 1];
}
}
"""
Problem: LeetCode 2770 - Maximum Number of Jumps to Reach the Last Index
Difficulty: Medium
Language: Python
Author: CodeByTushu
"""
from typing import List
class Solution:
def maximumJumps(self, nums: List[int], target: int) -> int:
n = len(nums)
dp = [-1] * n
dp[0] = 0
for i in range(1, n):
for j in range(i):
if dp[j] != -1:
diff = nums[i] - nums[j]
if -target <= diff <= target:
if dp[j] + 1 > dp[i]:
dp[i] = dp[j] + 1
return dp[n - 1]
/**
* Problem: LeetCode 2770 - Maximum Number of Jumps to Reach the Last Index
* Difficulty: Medium
* Language: C++
* Author: CodeByTushu
*/
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int maximumJumps(vector<int>& nums, int target) {
int n = nums.size();
vector<int> dp(n, -1);
dp[0] = 0;
for (int i = 1; i < n; ++i) {
for (int j = 0; j < i; ++j) {
if (dp[j] != -1) {
long long diff = (long long)nums[i] - nums[j];
if (diff >= -target && diff <= target) {
dp[i] = max(dp[i], dp[j] + 1);
}
}
}
}
return dp[n - 1];
}
};
/**
* Problem: LeetCode 2770 - Maximum Number of Jumps to Reach the Last Index
* Difficulty: Medium
* Language: JavaScript
* Author: CodeByTushu
*/
var maximumJumps = function(nums, target) {
const n = nums.length;
const dp = new Int32Array(n).fill(-1);
dp[0] = 0;
for (let i = 1; i < n; i++) {
for (let j = 0; j < i; j++) {
if (dp[j] !== -1) {
const diff = nums[i] - nums[j];
if (diff >= -target && diff <= target) {
if (dp[j] + 1 > dp[i]) {
dp[i] = dp[j] + 1;
}
}
}
}
}
return dp[n - 1];
};