welcome to my blog
LeetCode 1340. Jump Game V (Java版; Hard)
题目描述
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.
Notice that you can not jump outside of the array at any time.
Example 1:
Input: arr = [6,4,14,6,8,13,9,7,10,6,12], d = 2
Output: 4
Explanation: You can start at index 10. You can jump 10 --> 8 --> 6 --> 7 as shown.
Note that if you start at index 6 you can only jump to index 7. You cannot jump to index 5 because 13 > 9.
You cannot jump to index 4 because index 5 is between index 4 and 6 and 13 > 9.
Similarly You cannot jump from index 3 to index 2 or index 1.
Example 2:
Input: arr = [3,3,3,3,3], d = 3
Output: 1
Explanation: You can start at any index. You always cannot jump to any index.
Example 3:
Input: arr = [7,6,5,4,3,2,1], d = 1
Output: 7
Explanation: Start at index 0. You can visit all the indicies.
Example 4:
Input: arr = [7,1,7,1,7,1], d = 2
Output: 2
Example 5:
Input: arr = [66], d = 1
Output: 1
Constraints:
1 <= arr.length <= 1000
1 <= arr[i] <= 10^5
1 <= d <= arr.length
第一次做; 递归; 核心: 1)按照要求进行跳跃 2)使用flag进行记录处理过的点
class Solution {
public int maxJumps(int[] arr, int d) {
int n = arr.length;
if(n<=1){
return n;
}
int[] flag = new int[n];
int max = 1;
//从每个位置开始跳
for(int i=0; i<n; i++){
max = Math.max(core(arr, d, i, flag), max);
}
return max;
}
//从index跳跃时最多能跳多少次?
private int core(int[] arr, int d, int index, int[] flag){
//base case
if(index<0 || index>= arr.length){
return 0;
}
if(flag[index]!=0){
return flag[index];
}
flag[index] = 1;
int n = arr.length;
int max = 1;
//往右跳
for(int i=index + 1; i<=Math.min(n-1, index + d); i++){
//不满足跳跃条件, 没法继续往右跳了
if(arr[i]>=arr[index]){
break;
}
max = Math.max(max, core(arr, d, i,flag) + 1);
}
//往左跳
for(int i=index - 1; i>=Math.max(0, index-d); i--){
if(arr[i] >= arr[index]){
break;
}
max = Math.max(max, core(arr, d, i,flag) + 1);
}
flag[index] = max;
return max;
}
}
LeetCode优秀题解; 别想那么多,就挨着跳吧
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));
return res;
}
//参数d是数组的长度; for循环处理的比我简洁
private int dfs(int[] arr, int n, int d, int i, int[] dp) {
if (dp[i] != 0) return dp[i];
int res = 1;
for (int j = i + 1; j <= Math.min(i + d, n - 1) && arr[j] < arr[i]; ++j)
res = Math.max(res, 1 + dfs(arr, n, d, j, dp));
for (int j = i - 1; j >= Math.max(i - d, 0) && arr[j] < arr[i]; --j)
res = Math.max(res, 1 + dfs(arr, n, d, j, dp));
return dp[i] = res;
}