#546
Remove Boxes
HardArrayDynamic ProgrammingMemoizationDynamic ProgrammingMemoization
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³)
The optimal approach uses dynamic programming to store results of subproblems, which avoids redundant calculations. By memoizing the results, we can efficiently compute the maximum points for any configuration of boxes.
⚙️
Algorithm
3 steps- 1Step 1: Create a 3D DP array where dp[l][r][k] represents the maximum points obtainable from boxes[l] to boxes[r] with k additional boxes of the same color as boxes[r].
- 2Step 2: Iterate through all possible segments of boxes and fill the DP table based on previous results.
- 3Step 3: Return the value stored in dp[0][n-1][0] which gives the maximum points for the entire array.
solution.py14 lines
1def removeBoxes(boxes):
2 n = len(boxes)
3 dp = [[[0] * (n + 1) for _ in range(n)] for _ in range(n)]
4 for l in range(n - 1, -1, -1):
5 for r in range(l, n):
6 for k in range(n):
7 while r + 1 < n and boxes[r] == boxes[r + 1]:
8 r += 1
9 k += 1
10 dp[l][r][k] = max(dp[l][r][k], (k + 1) * (k + 1) + (dp[l][r - 1][0] if r > 0 else 0))
11 for m in range(l, r):
12 if boxes[m] == boxes[r]:
13 dp[l][r][k] = max(dp[l][r][k], dp[l][m][k] + dp[m + 1][r - 1][0])
14 return dp[0][n - 1][0]ℹ
Complexity note: The time complexity is O(n³) due to the three nested loops for the DP table, where n is the length of the boxes array. Each state in the DP table is computed based on previous states.
- 1The order of removing boxes can significantly affect the total score.
- 2Using memoization helps in avoiding recalculating results for the same state.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.