Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
You are given several boxes with different colors represented by different positive numbers.
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 k boxes, k >= 1), remove them and get k * k points.
Return the maximum points you can get.
Example 1:
Input: boxes = [1,3,2,2,2,3,4,3,1] Output: 23 Explanation: [1, 3, 2, 2, 2, 3, 4, 3, 1] ----> [1, 3, 3, 4, 3, 1] (3*3=9 points) ----> [1, 3, 3, 3, 1] (1*1=1 points) ----> [1, 1] (3*3=9 points) ----> [] (2*2=4 points)
Example 2:
Input: boxes = [1,1,1] Output: 9
Example 3:
Input: boxes = [1] Output: 1
Constraints:
1 <= boxes.length <= 1001 <= boxes[i] <= 100Problem summary: You are given several boxes with different colors represented by different positive numbers. 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 k boxes, k >= 1), remove them and get k * k points. Return the maximum points you can get.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Dynamic Programming
[1,3,2,2,2,3,4,3,1]
[1,1,1]
[1]
strange-printer)number-of-unique-flavors-after-sharing-k-candies)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #546: Remove Boxes
class Solution {
private int[][][] f;
private int[] b;
public int removeBoxes(int[] boxes) {
b = boxes;
int n = b.length;
f = new int[n][n][n];
return dfs(0, n - 1, 0);
}
private int dfs(int i, int j, int k) {
if (i > j) {
return 0;
}
while (i < j && b[j] == b[j - 1]) {
--j;
++k;
}
if (f[i][j][k] > 0) {
return f[i][j][k];
}
int ans = dfs(i, j - 1, 0) + (k + 1) * (k + 1);
for (int h = i; h < j; ++h) {
if (b[h] == b[j]) {
ans = Math.max(ans, dfs(h + 1, j - 1, 0) + dfs(i, h, k + 1));
}
}
f[i][j][k] = ans;
return ans;
}
}
// Accepted solution for LeetCode #546: Remove Boxes
func removeBoxes(boxes []int) int {
n := len(boxes)
f := make([][][]int, n)
for i := range f {
f[i] = make([][]int, n)
for j := range f[i] {
f[i][j] = make([]int, n)
}
}
var dfs func(i, j, k int) int
dfs = func(i, j, k int) int {
if i > j {
return 0
}
for i < j && boxes[j] == boxes[j-1] {
j, k = j-1, k+1
}
if f[i][j][k] > 0 {
return f[i][j][k]
}
ans := dfs(i, j-1, 0) + (k+1)*(k+1)
for h := i; h < j; h++ {
if boxes[h] == boxes[j] {
ans = max(ans, dfs(h+1, j-1, 0)+dfs(i, h, k+1))
}
}
f[i][j][k] = ans
return ans
}
return dfs(0, n-1, 0)
}
# Accepted solution for LeetCode #546: Remove Boxes
class Solution:
def removeBoxes(self, boxes: List[int]) -> int:
@cache
def dfs(i, j, k):
if i > j:
return 0
while i < j and boxes[j] == boxes[j - 1]:
j, k = j - 1, k + 1
ans = dfs(i, j - 1, 0) + (k + 1) * (k + 1)
for h in range(i, j):
if boxes[h] == boxes[j]:
ans = max(ans, dfs(h + 1, j - 1, 0) + dfs(i, h, k + 1))
return ans
n = len(boxes)
ans = dfs(0, n - 1, 0)
dfs.cache_clear()
return ans
// Accepted solution for LeetCode #546: Remove Boxes
struct Solution;
use std::collections::HashMap;
impl Solution {
fn remove_boxes(boxes: Vec<i32>) -> i32 {
let n = boxes.len();
let mut memo: HashMap<(usize, usize, usize), usize> = HashMap::new();
Self::dp(0, n, 0, &mut memo, &boxes) as i32
}
fn dp(
mut start: usize,
end: usize,
mut k: usize,
memo: &mut HashMap<(usize, usize, usize), usize>,
boxes: &[i32],
) -> usize {
if start == end {
return 0;
}
if let Some(&res) = memo.get(&(start, end, k)) {
return res;
}
while start + 1 < end && boxes[start + 1] == boxes[start] {
start += 1;
k += 1;
}
let mut res = Self::dp(start + 1, end, 0, memo, boxes) + (k + 1) * (k + 1);
for i in start + 1..end {
if boxes[i] == boxes[start] {
res = res.max(
Self::dp(i, end, k + 1, memo, boxes) + Self::dp(start + 1, i, 0, memo, boxes),
);
}
}
memo.insert((start, end, k), res);
res
}
}
#[test]
fn test() {
let boxes = vec![1, 3, 2, 2, 2, 3, 4, 3, 1];
let res = 23;
assert_eq!(Solution::remove_boxes(boxes), res);
}
// Accepted solution for LeetCode #546: Remove Boxes
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #546: Remove Boxes
// class Solution {
// private int[][][] f;
// private int[] b;
//
// public int removeBoxes(int[] boxes) {
// b = boxes;
// int n = b.length;
// f = new int[n][n][n];
// return dfs(0, n - 1, 0);
// }
//
// private int dfs(int i, int j, int k) {
// if (i > j) {
// return 0;
// }
// while (i < j && b[j] == b[j - 1]) {
// --j;
// ++k;
// }
// if (f[i][j][k] > 0) {
// return f[i][j][k];
// }
// int ans = dfs(i, j - 1, 0) + (k + 1) * (k + 1);
// for (int h = i; h < j; ++h) {
// if (b[h] == b[j]) {
// ans = Math.max(ans, dfs(h + 1, j - 1, 0) + dfs(i, h, k + 1));
// }
// }
// f[i][j][k] = ans;
// return ans;
// }
// }
Use this to step through a reusable interview workflow for this problem.
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.