Skip to content
Permalink
master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
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 (composed of k boxes, k >= 1), remove them and get k*k points.
Find the maximum points you can get.

Example 1:
Input:

[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)

My code:

class Solution(object):
    def removeBoxes(self, boxes):
        """
        :type boxes: List[int]
        :rtype: int
        """
        N = len(boxes)
        self.boxes = boxes
        self.dp = [[[-1]* N for i in range(N)] for j in range(N)]
        return self.search(0, N-1, 0)
        
    def search(self, l, r, k):
        if l > r:
            return 0
        
        if self.dp[l][r][k] != -1:
            return self.dp[l][r][k]
        
        while l < r and self.boxes[r] == self.boxes[r-1]:
            r -= 1
            k += 1
            
        self.dp[l][r][k] = self.search(l, r-1, 0) + (k + 1) * (k + 1)
        
        for i in range(l, r):#Here r is the updated r
            if self.boxes[i] == self.boxes[r]:
                #print('l %d r %d executed result %d'%(i,r,self.search(l,i,k+1)))
                self.dp[l][r][k] = max(self.dp[l][r][k], self.search(l,i,k+1)+self.search(i+1,r-1,0))#Here is the consideration that we finally get the combination of boxes[i]
                
        return self.dp[l][r][k]

Solution: https://leetcode.com/problems/remove-boxes/