[LeetCode] Jump Game V

1340. Jump Game V

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
vector<int> dp;
int dfs(vector<int>& arr, int& d, int st) {
if(dp[st] != -1) return dp[st];
int& res = dp[st] = 1;

for(int i = st + 1; i < arr.size() and i <= st + d and arr[i] < arr[st]; i++) {
res = max(res, dfs(arr,d,i) + 1);
}
for(int i = st - 1; i >= 0 and i >= st - d and arr[i] < arr[st]; i--) {
res = max(res, dfs(arr,d,i) + 1);
}

return res;
}
public:
int maxJumps(vector<int>& arr, int d) {
dp = vector<int>(arr.size(), -1);
int res = 0;
for(int i = 0; i < arr.size(); i++) {
res = max(res, dfs(arr, d, i));
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/10/PS/LeetCode/jump-game-v/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.