|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +/** |
| 4 | + * 546. Remove Boxes |
| 5 | + * |
| 6 | + * Given several boxes with different colors represented by different positive numbers. |
| 7 | + You may experience several rounds to remove boxes until there is no box left. |
| 8 | + 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. |
| 9 | + Find the maximum points you can get. |
| 10 | +
|
| 11 | + Example 1: |
| 12 | + Input: |
| 13 | +
|
| 14 | + [1, 3, 2, 2, 2, 3, 4, 3, 1] |
| 15 | + Output: |
| 16 | + 23 |
| 17 | +
|
| 18 | + Explanation: |
| 19 | + [1, 3, 2, 2, 2, 3, 4, 3, 1] |
| 20 | + ----> [1, 3, 3, 4, 3, 1] (3*3=9 points) |
| 21 | + ----> [1, 3, 3, 3, 1] (1*1=1 points) |
| 22 | + ----> [1, 1] (3*3=9 points) |
| 23 | + ----> [] (2*2=4 points) |
| 24 | + Note: The number of boxes n would not exceed 100. |
| 25 | + */ |
| 26 | +public class _546 { |
| 27 | + /**credit: https://leetcode.com/articles/remove-boxes/#approach-2-using-dp-with-memorizationaccepted*/ |
| 28 | + public int removeBoxes(int[] boxes) { |
| 29 | + int[][][] dp = new int[100][100][100]; |
| 30 | + return calculatePoints(boxes, dp, 0, boxes.length - 1, 0); |
| 31 | + } |
| 32 | + |
| 33 | + public int calculatePoints(int[] boxes, int[][][] dp, int l, int r, int k) { |
| 34 | + if (l > r) return 0; |
| 35 | + if (dp[l][r][k] != 0) return dp[l][r][k]; |
| 36 | + while (r > l && boxes[r] == boxes[r - 1]) { |
| 37 | + r--; |
| 38 | + k++; |
| 39 | + } |
| 40 | + dp[l][r][k] = calculatePoints(boxes, dp, l, r - 1, 0) + (k + 1) * (k + 1); |
| 41 | + for (int i = l; i < r; i++) { |
| 42 | + if (boxes[i] == boxes[r]) { |
| 43 | + dp[l][r][k] = Math.max(dp[l][r][k], calculatePoints(boxes, dp, l, i, k + 1) + calculatePoints(boxes, dp, i + 1, r - 1, 0)); |
| 44 | + } |
| 45 | + } |
| 46 | + return dp[l][r][k]; |
| 47 | + } |
| 48 | +} |
0 commit comments