Skip to content

Commit c045ae7

Browse files
committedMar 5, 2025
Add solution #546
1 parent afa619a commit c045ae7

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -434,6 +434,7 @@
434434
541|[Reverse String II](./0541-reverse-string-ii.js)|Easy|
435435
542|[01 Matrix](./0542-01-matrix.js)|Medium|
436436
543|[Diameter of Binary Tree](./0543-diameter-of-binary-tree.js)|Easy|
437+
546|[Remove Boxes](./0546-remove-boxes.js)|Hard|
437438
547|[Number of Provinces](./0547-number-of-provinces.js)|Medium|
438439
551|[Student Attendance Record I](./0551-student-attendance-record-i.js)|Easy|
439440
557|[Reverse Words in a String III](./0557-reverse-words-in-a-string-iii.js)|Easy|

‎solutions/0546-remove-boxes.js

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
* 546. Remove Boxes
3+
* https://leetcode.com/problems/remove-boxes/
4+
* Difficulty: Hard
5+
*
6+
* You are given several boxes with different colors represented by different positive numbers.
7+
*
8+
* You may experience several rounds to remove boxes until there is no box left. Each time you
9+
* can choose some continuous boxes with the same color (i.e., composed of k boxes, k >= 1),
10+
* remove them and get k * k points.
11+
*
12+
* Return the maximum points you can get.
13+
*/
14+
15+
/**
16+
* @param {number[]} boxes
17+
* @return {number}
18+
*/
19+
var removeBoxes = function(boxes) {
20+
const dp = new Array(boxes.length).fill().map(() => {
21+
return new Array(boxes.length).fill().map(() => new Array(boxes.length + 1).fill(0));
22+
});
23+
return dfs(0, boxes.length - 1, 0);
24+
25+
function dfs(l, r, k) {
26+
if (l > r) return 0;
27+
if (dp[l][r][k]) return dp[l][r][k];
28+
let i = l;
29+
let count = k + 1;
30+
while (i < r && boxes[i] === boxes[i + 1]) {
31+
i++;
32+
count++;
33+
}
34+
let max = count * count + dfs(i + 1, r, 0);
35+
for (let m = i + 1; m <= r; m++) {
36+
if (boxes[l] === boxes[m]) {
37+
max = Math.max(max, dfs(i + 1, m - 1, 0) + dfs(m, r, count));
38+
}
39+
}
40+
return dp[l][r][k] = max;
41+
}
42+
};

0 commit comments

Comments
 (0)
Please sign in to comment.