Intuition
Process bars from shortest to tallest. Each bar's answer depends only on shorter reachable bars, which are already computed when we get to it.
Explanation
Mental Model
Imagine each bar in a histogram. You can only jump downward to strictly shorter bars within distance d, and no taller bar can block the path. The question is: from which starting bar can you visit the most bars?
Since you always jump to shorter bars, the answer for a tall bar depends on already-computed answers for shorter bars. This gives us the DP ordering: process indices sorted by ascending bar height.
Algorithm
- Initialize
dp[i] = 1for every index (you always visit at least yourself). - Sort indices by
arr[i]ascending. - For each index
iin sorted order:- Scan left: for
x = 1, 2, ..., d, check indexi - x. Ifarr[i - x] >= arr[i], stop (this bar blocks further jumps). Otherwise,dp[i] = max(dp[i], dp[i - x] + 1). - Scan right: for
x = 1, 2, ..., d, check indexi + x. Ifarr[i + x] >= arr[i], stop. Otherwise,dp[i] = max(dp[i], dp[i + x] + 1).
- Scan left: for
- Return
max(dp).
Worked Example
arr = [6, 4, 14, 6, 8, 13, 9, 7, 10, 6, 12], d = 2
Indices sorted by value: [1(4), 0(6), 3(6), 9(6), 7(7), 4(8), 6(9), 8(10), 10(12), 5(13), 2(14)]
| Process idx | val | Left scan | Right scan | dp[i] |
|---|---|---|---|---|
| 1 | 4 | idx 0: 6>=4, stop | idx 2: 14>=4, stop | 1 |
| 0 | 6 | — | idx 1: 4<6, dp=2 | 2 |
| 3 | 6 | idx 2: 14>=6, stop | idx 4: 8>=6, stop | 1 |
| 9 | 6 | idx 8: 10>=6, stop | idx 10: 12>=6, stop | 1 |
| 7 | 7 | idx 6: 9>=7, stop | idx 8: 10>=7, stop | 1 |
| 4 | 8 | idx 3: 6<8, dp=2 | idx 5: 13>=8, stop | 2 |
| 6 | 9 | idx 5: 13>=9, stop | idx 7: 7<9, dp=2 | 2 |
| 8 | 10 | idx 7: 7<10 dp=2; idx 6: 9<10 dp=3 | idx 9: 6<10 dp=2 | 3 |
| 10 | 12 | idx 9: 6<12 dp=2; idx 8: 10<12 dp=4 | — | 4 |
| 5 | 13 | idx 4: 8<13 dp=3; idx 3: 6<13 dp=2 | idx 6: 9<13 dp=3 | 3 |
| 2 | 14 | idx 1: 4<14 dp=2; idx 0: 6<14 dp=3 | idx 3: 6<14 dp=2 | 3 |
max(dp) = 4 at index 10. The path is 10 -> 8 -> 6 -> 7.
Edge Cases
- All equal values: No jumps possible since you need strictly smaller. Answer = 1.
- Strictly decreasing with d=1: Every bar can jump to the next. Answer = n.
- Single element: Answer = 1.
Complexity
- Time: O(n * d) — for each of n indices, we scan at most 2d neighbors.
- Space: O(n) — the dp array plus the sorted index list.
Implementation
import java.util.Arrays;
class Solution {
public int maxJumps(int[] arr, int d) {
int n = arr.length;
int[] dp = new int[n];
Arrays.fill(dp, 1);
Integer[] order = new Integer[n];
for (int i = 0; i < n; i++) order[i] = i;
Arrays.sort(order, (a, b) -> arr[a] - arr[b]);
for (int i : order) {
for (int x = 1; x <= d; x++) {
int j = i - x;
if (j < 0 || arr[j] >= arr[i]) break;
dp[i] = Math.max(dp[i], dp[j] + 1);
}
for (int x = 1; x <= d; x++) {
int j = i + x;
if (j >= n || arr[j] >= arr[i]) break;
dp[i] = Math.max(dp[i], dp[j] + 1);
}
}
int ans = 0;
for (int v : dp) ans = Math.max(ans, v);
return ans;
}
}