#2770
Maximum Number of Jumps to Reach the Last Index
MediumArrayDynamic ProgrammingDynamic ProgrammingGreedy Algorithms
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n²) |
| Space | O(n) | O(n) |
💡
Intuition
Time O(n²)Space O(n)
The optimal approach uses dynamic programming to store the maximum number of jumps to each index. This way, we avoid redundant calculations and efficiently find the solution.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a dp array of size n with all values set to -1, except dp[0] which is set to 0.
- 2Step 2: Iterate through each index i from 0 to n-1.
- 3Step 3: For each index i, check all possible jumps to index j (i < j < n) that satisfy the target condition and update dp[j] accordingly.
solution.py13 lines
1# Full working Python code
2
3def maxJumps(nums, target):
4 n = len(nums)
5 dp = [-1] * n
6 dp[0] = 0
7 for i in range(n):
8 if dp[i] == -1:
9 continue
10 for j in range(i + 1, n):
11 if nums[j] - nums[i] <= target:
12 dp[j] = max(dp[j], dp[i] + 1)
13 return dp[-1]ℹ
Complexity note: The time complexity remains O(n²) due to the nested loops, but we significantly reduce redundant calculations by storing results. The space complexity is O(n) for the dp array.
- 1Dynamic programming helps avoid redundant calculations.
- 2Understanding the jump conditions is crucial for optimizing the solution.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.