Jump Game V Problem
Description
LeetCode Problem 1340.
Given an array of integers arr and an integer d. In one step you can jump from index i to index:
i + xwhere:i + x < arr.lengthand0 < x <= d.i - xwhere:i - x >= 0and0 < 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 = 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.
Constraints:
1 <= arr.length <= 10001 <= arr[i] <= 10^51 <= d <= arr.length
Solution
Approach: Dynamic Programming in Height Order
Let f[i] be the most indices we can visit when we start at i. From i, walk left one index at a time: each j with arr[j] < arr[i] and |i - j| <= d is a valid jump target, and the walk must stop at the first bar that is not lower than arr[i], because that bar blocks every index behind it. The same goes for the right side. Then
f[i] = 1 + max(f[j]) over all those targets j, or 1 if there are none.
Every jump goes to a strictly lower bar, so f[i] only depends on lower bars. If we handle the indices in increasing order of height, every f[j] we need is already final. Bars of equal height never depend on each other, since an equal bar stops the walk. The answer is the largest f[i].
(A memoized DFS from every index computes the same table; sorting just makes the order explicit and avoids recursion.)
Complexity: O(n log n + n·d) time: the sort, then at most d steps in each direction from each index. O(n) extra space.
class Solution:
def maxJumps(self, arr: List[int], d: int) -> int:
n = len(arr)
f = [1] * n # f[i] = most indices we can visit starting at i
# Every jump goes to a lower bar, so handle the bars from lowest to highest.
for i in sorted(range(n), key=lambda i: arr[i]):
for step in (-1, 1):
j = i + step
# Stop at the edge, at distance d, or at a bar that is not lower.
while 0 <= j < n and abs(j - i) <= d and arr[j] < arr[i]:
f[i] = max(f[i], f[j] + 1)
j += step
return max(f)