-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathremove-boxes.go
58 lines (43 loc) · 858 Bytes
/
remove-boxes.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package removeboxes
func removeBoxes(boxes []int) int {
n := len(boxes)
dp := make([][][]int, n)
for i := range dp {
dp[i] = make([][]int, n)
for j := range dp[i] {
dp[i][j] = make([]int, n)
}
}
return remove(boxes, 0, n-1, 0, dp)
}
func remove(boxes []int, i int, j int, k int, dp [][][]int) int {
if i > j {
return 0
}
if i == j {
return (k + 1) * (k + 1)
}
if dp[i][j][k] != 0 {
return dp[i][j][k]
}
count := 0
left := i
for left <= j && boxes[left] == boxes[i] {
left++
count++
}
start := left
res := (count+k)*(count+k) + remove(boxes, start, j, 0, dp)
m := left
for m <= j {
if boxes[m] == boxes[i] && boxes[m-1] != boxes[i] {
newRes := remove(boxes, start, m-1, 0, dp) + remove(boxes, m, j, count+k, dp)
if newRes > res {
res = newRes
}
}
m++
}
dp[i][j][k] = res
return res
}