#3660
Jump Game IX
MediumArrayDynamic ProgrammingGraph TraversalDynamic Programming
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Use a stack to efficiently track reachable values. By processing indices in reverse, we can ensure that we always find the maximum value reachable from each index.
⚙️
Algorithm
3 steps- 1Step 1: Initialize an empty stack and an answer array filled with zeros.
- 2Step 2: Traverse the array from right to left, using the stack to track potential maximum values.
- 3Step 3: For each index, pop from the stack until the top value is valid, then update the answer.
solution.py10 lines
1def jump_game_ix(nums):
2 n = len(nums)
3 ans = [0] * n
4 stack = []
5 for i in range(n - 1, -1, -1):
6 while stack and (stack[-1] >= nums[i] or (i < stack[-1] and nums[stack[-1]] < nums[i])):
7 stack.pop()
8 ans[i] = max(nums[i], stack[-1] if stack else nums[i])
9 stack.append(nums[i])
10 return ansℹ
Complexity note: We traverse the array once and use a stack to store potential maximums, leading to linear complexity.
- 1The problem can be visualized as a directed graph of jumps.
- 2Using a stack allows efficient tracking of maximum reachable values.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.