Skip to content

Commit 48017b9

Browse files
refactor 312
1 parent cf6edfd commit 48017b9

File tree

2 files changed

+60
-15
lines changed

2 files changed

+60
-15
lines changed

src/main/java/com/fishercoder/solutions/_312.java

+27-15
Original file line numberDiff line numberDiff line change
@@ -3,27 +3,39 @@
33
public class _312 {
44

55
public static class Solution1 {
6-
public int maxCoins(int[] iNums) {
7-
int[] nums = new int[iNums.length + 2];
6+
/**
7+
* credit: https://leetcode.com/problems/burst-balloons/discuss/76228/Share-some-analysis-and-explanations
8+
* <p>
9+
* Divide and conquer with memoization
10+
*/
11+
public int maxCoins(int[] nums) {
12+
int[] input = new int[nums.length + 2];
813
int n = 1;
9-
for (int x : iNums) {
14+
for (int x : nums) {
1015
if (x > 0) {
11-
nums[n++] = x;
16+
input[n++] = x;
1217
}
1318
}
14-
nums[0] = nums[n++] = 1;
19+
input[0] = 1;
20+
input[n++] = 1;
1521

16-
int[][] dp = new int[n][n];
17-
for (int k = 2; k < n; ++k) {
18-
for (int left = 0; left < n - k; ++left) {
19-
int right = left + k;
20-
for (int i = left + 1; i < right; ++i) {
21-
dp[left][right] = Math.max(dp[left][right],
22-
nums[left] * nums[i] * nums[right] + dp[left][i] + dp[i][right]);
23-
}
24-
}
22+
int[][] memo = new int[n][n];
23+
return burst(memo, input, 0, n - 1);
24+
}
25+
26+
private int burst(int[][] memo, int[] nums, int left, int right) {
27+
if (left + 1 == right) {
28+
return 0;
29+
}
30+
if (memo[left][right] > 0) {
31+
return memo[left][right];
32+
}
33+
int ans = 0;
34+
for (int i = left + 1; i < right; i++) {
35+
ans = Math.max(ans, nums[left] * nums[i] * nums[right] + burst(memo, nums, left, i) + burst(memo, nums, i, right));
2536
}
26-
return dp[0][n - 1];
37+
memo[left][right] = ans;
38+
return ans;
2739
}
2840
}
2941
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package com.fishercoder;
2+
3+
import com.fishercoder.solutions._312;
4+
import org.junit.BeforeClass;
5+
import org.junit.Test;
6+
7+
import static org.junit.Assert.assertEquals;
8+
9+
public class _312Test {
10+
private static _312.Solution1 solution1;
11+
private static int[] nums;
12+
private static int expected;
13+
14+
@BeforeClass
15+
public static void setup() {
16+
solution1 = new _312.Solution1();
17+
}
18+
19+
@Test
20+
public void test1() {
21+
nums = new int[]{3, 1, 5, 8};
22+
expected = 167;
23+
assertEquals(expected, solution1.maxCoins(nums));
24+
}
25+
26+
@Test
27+
public void test2() {
28+
nums = new int[]{1, 5};
29+
expected = 10;
30+
assertEquals(expected, solution1.maxCoins(nums));
31+
}
32+
33+
}

0 commit comments

Comments
 (0)