leetcode2770. The maximum number of jumps required to reach the end subscript

  • https://leetcode.cn/problems/maximum-number-of-jumps-to-reach-the-last-index/

  • You are given a zero-based array nums of n integers and an integer target.

  • Your initial position is at subscript 0. In one step, you can jump from index i to any index j that satisfies the following conditions:

  • 0 <= i < j < n

  • -target <= nums[j] - nums[i] <= target

  • 最大Returns the number of hops required to reach index n - 1 . Returns -1 if index n - 1 cannot be reached.

示例 1:

输入:nums = [1,3,6,4,1,2], target = 2
输出:3
解释:要想以最大跳跃次数从下标 0 到下标 n - 1 ,可以按下述跳跃序列执行操作:
- 从下标 0 跳跃到下标 1 。 
- 从下标 1 跳跃到下标 3 。 
- 从下标 3 跳跃到下标 5 。 
可以证明,从 0 到 n - 1 的所有方案中,不存在比 3 步更长的跳跃序列。因此,答案是 3 。 
示例 2:

输入:nums = [1,3,6,4,1,2], target = 3
输出:5
解释:要想以最大跳跃次数从下标 0 到下标 n - 1 ,可以按下述跳跃序列执行操作:
- 从下标 0 跳跃到下标 1 。 
- 从下标 1 跳跃到下标 2 。 
- 从下标 2 跳跃到下标 3 。 
- 从下标 3 跳跃到下标 4 。 
- 从下标 4 跳跃到下标 5 。 
可以证明,从 0 到 n - 1 的所有方案中,不存在比 5 步更长的跳跃序列。因此,答案是 5 。 
示例 3:

输入:nums = [1,3,6,4,1,2], target = 0
输出:-1
解释:可以证明不存在从 0 到 n - 1 的跳跃序列。因此,答案是 -1 。 
 

提示:

2 <= nums.length == n <= 1000
-109 <= nums[i] <= 109
0 <= target <= 2 * 109

answer

  • If you are looking for the minimum number of jumps required to reach the end subscript, you can assume that dp[i] is the minimum number of steps required to reach the current position and then use min (reachable position) + 1
  • Finding the maximum value can also be done in the same way:
class Solution {
    
    
public:
    int maximumJumps(vector<int> &nums, int target) {
    
    
        int n = nums.size();
        vector<int> p(n, INT32_MIN);
        p[0] = 0;
        for (int i = 1; i < n; i++)
            for (int j = 0; j < i; j++)
                if (p[j] != INT32_MIN && abs(nums[i] - nums[j]) <= target)
                    p[i] = max(p[i], p[j] + 1);
        return p[n - 1] == INT32_MIN ? -1 : p[n - 1];
    }
};

Guess you like

Origin blog.csdn.net/ResumeProject/article/details/132030465