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

就是只能往比自己低的地方跳 求最多的跳跃次数。但是我们给了一个数字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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值