[LeetCode] Maximum Number of Jumps to Reach the Last Index

2770. Maximum Number of Jumps to Reach the Last Index

You are given a 0-indexed array nums of n integers and an integer target.

You are initially positioned at index 0. In one step, you can jump from index i to any index j such that:

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

Return the maximum number of jumps you can make to reach index n - 1.

If there is no way to reach index n - 1, return -1.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
int maximumJumps(vector<int>& nums, int target) {
vector<long long> res(nums.size(), INT_MIN);
res[0] = 0;
for(int i = 0; i < nums.size(); i++) {
for(int j = i + 1; j < nums.size(); j++) {
if(-target <= nums[j] - nums[i] and nums[j] - nums[i] <= target) {
res[j] = max(res[j], res[i] + 1);
}
}
}
if(res.back() <= 0) return -1;
return res.back();
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/07/09/PS/LeetCode/maximum-number-of-jumps-to-reach-the-last-index/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.