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] <= 100When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you have a line of colored toy boxes and you want to score the maximum points by removing matching groups. The brute force approach involves trying every single possible sequence of box removals to see which path gives you the highest total score.
Here's how the algorithm would work step-by-step:
class Solution:
def removeBoxes(self, boxes: list[int]) -> int:
memoization_table = {}
def calculate_maximum_points(box_segment, streak_count):
if not box_segment:
return 0
state_tuple = (tuple(box_segment), streak_count)
if state_tuple in memoization_table:
return memoization_table[state_tuple]
current_box_color = box_segment[0]
segment_index = 0
while segment_index < len(box_segment) and box_segment[segment_index] == current_box_color:
segment_index += 1
boxes_to_remove = segment_index
total_streak = streak_count + boxes_to_remove
max_score = (total_streak * total_streak) + calculate_maximum_points(box_segment[segment_index:], 0)
# We branch out by merging identical non-adjacent colors to maximize future clear combos
for split_index in range(segment_index, len(box_segment)):
if box_segment[split_index] == current_box_color:
points_from_split = (
calculate_maximum_points(box_segment[segment_index:split_index], 0)
+ calculate_maximum_points(box_segment[split_index:], total_streak)
)
max_score = max(max_score, points_from_split)
memoization_table[state_tuple] = max_score
return max_score
return calculate_maximum_points(boxes, 0)To remove colored boxes for the highest score, the best strategy is to break the puzzle down into smaller sub-puzzles using memoization, remembering the history of identical boxes waiting nearby. Instead of just looking at a contiguous block, we must account for bonus points that come from dragging matching boxes together from the outside.
Here's how the algorithm would work step-by-step:
class Solution:
def removeBoxes(self, boxes: list[int]) -> int:
memoization_table = {}
def calculate_max_score(left_index, right_index, consecutive_count):
if left_index > right_index:
return 0
state_key = (left_index, right_index, consecutive_count)
if state_key in memoization_table:
return memoization_table[state_key]
# We optimize by grouping adjacent identical boxes to maximize the square points bonus.
while left_index < right_index and boxes[left_index] == boxes[left_index + 1]:
left_index += 1
consecutive_count += 1
max_score = (consecutive_count + 1) * (consecutive_count + 1) + calculate_max_score(left_index + 1, right_index, 0)
# We split the problem when matching distant boxes to merge them with the current group.
for candidate_index in range(left_index + 1, right_index + 1):
if boxes[candidate_index] == boxes[left_index]:
current_score = calculate_max_score(left_index + 1, candidate_index - 1, 0) + calculate_max_score(candidate_index, right_index, consecutive_count + 1)
if current_score > max_score:
max_score = current_score
# We cache computed results to avoid redundant calculations across overlapping sub-problems.
memoization_table[state_key] = max_score
return max_score
return calculate_max_score(0, len(boxes) - 1, 0)| Case | How to Handle |
|---|---|
| Empty or null input array of boxes | Return zero points immediately since no boxes exist to be removed. |
| Array containing a single box | Return one point since removing a single box yields one squared. |
| Array with all boxes of the same color | Square the total length of the array to compute the maximum score from a single removal. |
| Alternating colors requiring delayed removal for maximum score | Dynamic programming state definition must track contiguous identical color counts to accumulate points correctly across non-contiguous merges. |
| Maximum allowed input size leading to high time and space complexity | Memoization or an optimized three dimensional dynamic programming table prevents redundant subproblem calculations. |
| Deep recursion stack limits when processing long inputs | Memoized top-down recursion or bottom-up iterative DP ensures safe execution without stack overflow errors. |
| Integer overflow from squaring large contiguous box groups | Use standard 32-bit or 64-bit integer types capable of holding maximum possible score values. |