1344. Jump Game V

https://leetcode.com/problems/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.

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

对于数组arr和整数d,能从任何一个点开始,每步能最远跳到j 属于[i - d, i + d],且(i, j]中任何一个点arr[k]不能小于等于arr[i],问这么走最多能覆盖多少元素。每步只能从值高走到低,因此对arr做排序并从小到大遍历,dp[i]表示从i出发最多能覆盖多少点,对i的action为从[i - d, i + d]找dp最多的点j,让i蹦到j并以此更新dp[i]。

时间复杂度O(NlgN + ND)。也可以用top-bottom 的DFS + memo,把dfs的中间结果存在dp里,时间复杂度O(ND)。

参考自

class Solution {
public:
    int maxJumps(vector<int>& arr, int d) {
        const int N = arr.size();
        vector<int> dp(N, 1);
        vector<vector<int>> nums(N, vector<int>(2));
        for (int i = 0; i < N; ++i) {
            nums[i][0] = arr[i];
            nums[i][1] = i;
        }
        sort(nums.begin(), nums.end(), [](const auto &a, const auto &b) {
            return a[0] < b[0];
        });
        int res = 0;
        for (const auto &num : nums) {
            int i = num[1];
            for (int j = i + 1; j <= min(i + d, N - 1); ++j) {
                if (arr[j] >= arr[i]) break;
                dp[i] = max(dp[i], dp[j] + 1);
            } 
            for (int j = i - 1; j >= max(i - d, 0); --j) {
                if (arr[j] >= arr[i]) break;
                dp[i] = max(dp[i], dp[j] + 1);
            } 
            res = max(res, dp[i]);
        }
        return res;
    }
};

Last updated