#1696
Jump Game VI
MediumArrayDynamic ProgrammingQueueHeap (Priority Queue)Monotonic QueueDynamic ProgrammingGreedy Algorithms
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log k) |
| Space | O(n) | O(n) |
💡
Intuition
Time O(n log k)Space O(n)
The optimal solution uses dynamic programming and a max-heap to efficiently track the maximum scores from reachable indices. This avoids redundant calculations and speeds up the process.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a dp array where dp[i] represents the maximum score to reach the end starting from index i.
- 2Step 2: Use a max-heap to keep track of the maximum dp values within the last k indices.
- 3Step 3: Iterate from the end of the array to the beginning, updating dp[i] based on the maximum value from the heap and the current index's value.
solution.py14 lines
1import heapq
2
3def maxScore(nums, k):
4 n = len(nums)
5 dp = [0] * n
6 max_heap = []
7 dp[-1] = nums[-1]
8 heapq.heappush(max_heap, (-dp[-1], n - 1))
9 for i in range(n - 2, -1, -1):
10 while max_heap and max_heap[0][1] > i + k:
11 heapq.heappop(max_heap)
12 dp[i] = nums[i] + (-max_heap[0][0])
13 heapq.heappush(max_heap, (-dp[i], i))
14 return dp[0]ℹ
Complexity note: The time complexity is O(n log k) due to the operations on the max-heap, where we maintain at most k elements at any time.
- 1Dynamic programming can significantly reduce the number of calculations by storing intermediate results.
- 2Using a max-heap allows us to efficiently track the best scores within the allowed jump range.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.