LeetCode-1344. Jump Game V

网友投稿 669 2022-08-25

LeetCode-1344. Jump Game V

LeetCode-1344. 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.

Example 1:

Input: arr = [6,4,14,6,8,13,9,7,10,6,12], d = 2Output: 4Explanation: 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 = 3Output: 1Explanation: 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 = 1Output: 7Explanation: Start at index 0. You can visit all the indicies.

Example 4:

Input: arr = [7,1,7,1,7,1], d = 2Output: 2

Example 5:

Input: arr = [66], d = 1Output: 1

Constraints:

​​1 <= arr.length <= 1000​​​​1 <= arr[i] <= 10^5​​​​1 <= d <= arr.length​​

​​题解:​​

​​类似于329道题:二维矩阵的最长递增路径,记忆化搜索,存储每个顶点可以到达的最大值。​​

class Solution {public: int dfs(vector &arr, int d, int k, vector &dp) { if (dp[k] != -1) { return dp[k]; } int len = 0; int left = max(0, k - d), right = min((int)(arr.size() - 1), k + d); for (int l = k - 1; l >= left && arr[l] < arr[k]; l--) { len = max(len, dfs(arr, d, l, dp)); } for (int r = k + 1; r <= right && arr[r] < arr[k]; r++) { len = max(len, dfs(arr, d, r, dp)); } dp[k] = len + 1; return dp[k]; } int maxJumps(vector& arr, int d) { int n = arr.size(); int res = 0; vector dp(n, -1); for (int i = 0; i < n; i++) { dfs(arr, d, i, dp); } for (int i = 0; i < n; i++) { res = max(res, dp[i]); } return res; }};

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:LeetCode-1323. Maximum 69 Number
下一篇:perl 解析xml ,json文件及curl工具的使用
相关文章

 发表评论

暂时没有评论,来抢沙发吧~