Given an array of integers arr and an integer d. In one step you can jump from index i to index:
i + x where: i + x < arr.length and 0 < x <= d.
i - x where: i - x >= 0 and 0 < x <= d.
In addition, you can only jump from index i to index j if arr[i] > arr[j] and arr[i] > arr[k] for all indices k between i and j (More formally min(i, j) < k < max(i, j)).
You can choose any index of the array and start jumping. Return the maximum number of indices you can visit.
就是只能往比自己低的地方跳 求最多的跳跃次数。但是我们给了一个数字d 表示我们往右边跳最多跳d 往左挑最多也跨越d个
//memo + dfs
//we try to starting at every index to find each of them the farthest they can get
//but we don't have to calcuate every one from begining to the end, why? for example
//say we get the max step if we starting from index i
//and when we need to calculate the max step starting at j, and it take a few steps, and it goes to i, so instead of keep going, we can just use the max step of i we previouly used.
class Solution {
public int maxJumps(int[] arr, int d) {
int n = arr.length;
int dp[] = new int[n];
int res = 1;
for (int i = 0; i < n; i++)
res = Math.max(res, dfs(arr, n, d, i, dp)); //res is the global maximal
return res;
}
private int dfs(int[] arr, int n, int d, int i, int[] dp) { //dfs returns the maxstep starting from index i
if (dp[i] != 0) return dp[i];
int res = 1;
int rightJump = 1;
int leftJump = 1;
for (int j = i + 1; j <= Math.min(i + d, n - 1) && arr[j] < arr[i]; j++) {
rightJump = Math.max(rightJump, 1 + dfs(arr, n, d, j, dp));
}
for (int j = i - 1; j >= Math.max(i - d, 0) && arr[j] < arr[i]; j--) {
leftJump = Math.max(leftJump, 1 + dfs(arr, n, d, j, dp));
}
dp[i] = Math.max(rightJump, leftJump); //dp[i] choose the maximum between left Jump and right jump
return dp[i];
}
}
actually, dp should be called memo instead.