Jump Game V - Problem

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 & Output

Example 1 — Basic Case
$ Input: arr = [6,4,14,6,9], d = 2
Output: 3
💡 Note: Start at index 2 (value 14): 14→6→4, visiting 3 indices. From 14 we can jump to positions with values 6,6,9 within distance 2. From 6 we can jump to 4.
Example 2 — Limited Jumps
$ Input: arr = [3,3,3,3,3], d = 3
Output: 1
💡 Note: All values are equal, so no valid jumps possible since we need arr[i] > arr[j]. Can only visit 1 index.
Example 3 — Blocked Path
$ Input: arr = [2,6,4], d = 1
Output: 2
💡 Note: From index 1 (value 6), can jump to index 0 (value 2) or index 2 (value 4). Maximum path is 2 indices.

Constraints

  • 1 ≤ arr.length ≤ 1000
  • 1 ≤ d ≤ arr.length
  • 1 ≤ arr[i] ≤ 105

Visualization

Tap to expand
Jump Game V - Topological Sort + DP INPUT 6 i=0 4 i=1 14 i=2 6 i=3 9 i=4 arr = [6, 4, 14, 6, 9] d = 2 (max jump dist) Can jump if arr[i] > arr[j] and no blocking bars between Jump distance: 1 to d steps ALGORITHM STEPS 1 Sort by Height Process indices by arr value [4,6,6,9,14] -- indices: 1,0,3,4,2 2 Build DAG Edges Higher bars can jump to lower 2-->0,1,3,4 | 4-->3 | 0-->1 3 Topological Order Process smallest first Order: 1 --> 0 --> 3 --> 4 --> 2 4 DP Calculation dp[i] = 1 + max(dp[reachable]) DP Values i=0 i=1 i=2 i=3 i=4 2 1 3 1 2 max(dp) = 3 at index 2 FINAL RESULT Optimal Jump Path 6 4 14 START 6 9 Jump Sequence: 14 --> 6 --> 4 (index 2 --> 0 --> 1) Output: 3 OK - Maximum indices visited Starting from index 2 (value 14) Key Insight: The problem forms a DAG where edges go from higher to lower bars. By sorting indices by height and processing in topological order (smallest first), we ensure all reachable destinations are computed before each source. DP relation: dp[i] = 1 + max(dp[j]) for all valid jumps from i to j. Time: O(n*d) TutorialsPoint - Jump Game V | Topological Sort + Dynamic Programming
Asked in
Facebook 45 Google 38 Amazon 32
28.4K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen