#1340
Jump Game V
HardArrayDynamic ProgrammingSortingDynamic ProgrammingSorting
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
The optimal solution uses dynamic programming to store the maximum jumps possible from each index, allowing us to avoid redundant calculations. We can fill this dp array by checking all possible jumps efficiently.
⚙️
Algorithm
4 steps- 1Step 1: Initialize a dp array where dp[i] represents the maximum jumps from index i.
- 2Step 2: Sort the indices based on the values in arr to ensure we process larger values first.
- 3Step 3: For each index, check all possible jumps (both left and right) within the distance d and update the dp array accordingly.
- 4Step 4: The result is the maximum value in the dp array.
solution.py25 lines
1# Full working Python code
2
3def maxJumps(arr, d):
4 n = len(arr)
5 dp = [1] * n # Each index can at least reach itself
6 indices = sorted(range(n), key=lambda i: arr[i]) # Sort indices based on arr values
7
8 for i in indices:
9 # Check right jumps
10 for x in range(1, d + 1):
11 if i + x < n and arr[i] > arr[i + x]:
12 dp[i] = max(dp[i], 1 + dp[i + x])
13 else:
14 break
15 # Check left jumps
16 for x in range(1, d + 1):
17 if i - x >= 0 and arr[i] > arr[i - x]:
18 dp[i] = max(dp[i], 1 + dp[i - x])
19 else:
20 break
21
22 return max(dp)
23
24# Example usage
25print(maxJumps([6,4,14,6,8,13,9,7,10,6,12], 2))ℹ
Complexity note: The time complexity is O(n log n) due to sorting the indices, while the space complexity is O(n) for the dp array.
- 1Dynamic programming allows us to build solutions incrementally, avoiding redundant calculations.
- 2Sorting indices based on values helps ensure we always process larger values first, maximizing potential jumps.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.