Skip to content

Commit fba71c0

Browse files
committed
[LeetCode Sync] Runtime - 694 ms (73.15%), Memory - 36.9 MB (61.35%)
1 parent f3f6f8f commit fba71c0

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
<p>You are given several <code>boxes</code> with different colors represented by different positive numbers.</p>
2+
3+
<p>You may experience several rounds to remove boxes until there is no box left. Each time you can choose some continuous boxes with the same color (i.e., composed of <code>k</code> boxes, <code>k &gt;= 1</code>), remove them and get <code>k * k</code> points.</p>
4+
5+
<p>Return <em>the maximum points you can get</em>.</p>
6+
7+
<p>&nbsp;</p>
8+
<p><strong class="example">Example 1:</strong></p>
9+
10+
<pre>
11+
<strong>Input:</strong> boxes = [1,3,2,2,2,3,4,3,1]
12+
<strong>Output:</strong> 23
13+
<strong>Explanation:</strong>
14+
[1, 3, 2, 2, 2, 3, 4, 3, 1]
15+
----&gt; [1, 3, 3, 4, 3, 1] (3*3=9 points)
16+
----&gt; [1, 3, 3, 3, 1] (1*1=1 points)
17+
----&gt; [1, 1] (3*3=9 points)
18+
----&gt; [] (2*2=4 points)
19+
</pre>
20+
21+
<p><strong class="example">Example 2:</strong></p>
22+
23+
<pre>
24+
<strong>Input:</strong> boxes = [1,1,1]
25+
<strong>Output:</strong> 9
26+
</pre>
27+
28+
<p><strong class="example">Example 3:</strong></p>
29+
30+
<pre>
31+
<strong>Input:</strong> boxes = [1]
32+
<strong>Output:</strong> 1
33+
</pre>
34+
35+
<p>&nbsp;</p>
36+
<p><strong>Constraints:</strong></p>
37+
38+
<ul>
39+
<li><code>1 &lt;= boxes.length &lt;= 100</code></li>
40+
<li><code>1 &lt;= boxes[i]&nbsp;&lt;= 100</code></li>
41+
</ul>
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
class Solution:
2+
def removeBoxes(self, boxes: List[int]) -> int:
3+
n = len(boxes)
4+
5+
@cache
6+
def dfs(i: int, j: int, k: int) -> int:
7+
if i > j:
8+
return 0
9+
while i < j and boxes[j] == boxes[j - 1]:
10+
j, k = j - 1, k + 1
11+
result = dfs(i, j - 1, 0) + ((k + 1)**2)
12+
for val in range(i, j):
13+
if boxes[j] == boxes[val]:
14+
result = max(result, dfs(val + 1, j - 1, 0) + dfs(i, val, k + 1))
15+
return result
16+
17+
return dfs(0, n - 1, 0)

0 commit comments

Comments
 (0)