public class Solution {
public int maxCoins(int[] nums) {
if(nums == null || nums.length < 1) return 0;
ArrayList<Integer> numsArray = new ArrayList<Integer>();
numsArray.add(1);
for (int num : nums) {
numsArray.add(num);
}
numsArray.add(1);
int len = nums.length;
int[][] dp = new int[len + 2][len + 2];
// for(int i = 0; i <= len; i++) {
// Arrays.fill(dp[i], 1);
// }
for (int i = len; i >= 1; i--) {
for (int j = i; j <= len; j++) {
for (int k = i; k <= j; k++) {
dp[i][j] = Math.max(dp[i][j], dp[i][k - 1] + numsArray.get(i - 1) * numsArray.get(k) * numsArray.get(j + 1) + dp[k + 1][j]);
}
}
}
return dp[1][len];
}
}
public class Solution {
public int maxCoins(int[] nums) {
if (nums == null || nums.length == 0) return 0;
// dp[i][j] means the maximal coins for range [i...j]. In this case, our final answer is dp[0][nums.length - 1].
int[][] dp = new int[nums.length][nums.length];
for (int len = 1; len <= nums.length; len++) {
for (int start = 0; start <= nums.length - len; start++) {
int end = start + len - 1;
for (int i = start; i <= end; i++) {
int coins = nums[i] * getValue(nums, start - 1) * getValue(nums, end + 1);
coins += i != start ? dp[start][i - 1] : 0; // If not first one, we can add subrange on its left.
coins += i != end ? dp[i + 1][end] : 0; // If not last one, we can add subrange on its right
dp[start][end] = Math.max(dp[start][end], coins);
}
}
}
return dp[0][nums.length - 1];
}
private int getValue(int[] nums, int i) { // Deal with num[-1] and num[num.length]
if (i < 0 || i >= nums.length) {
return 1;
}
return nums[i];
}
}
public class Solution {
public int maxCoins(int[] iNums) {
int[] nums = new int[iNums.length + 2];
int n = 1;
for (int x : iNums) if (x > 0) nums[n++] = x;
nums[0] = nums[n++] = 1;
int[][] memo = new int[n][n];
return burst(memo, nums, 0, n - 1);
}
private int burst(int[][] memo, int[] nums, int i, int j) {
if (i+1 == j) return 0;
if (memo[i][j] != 0) {
return memo[i][j];
}
int max = 0;
for (int x = i+1; x < j; ++x) {
max = Math.max(max, nums[i] * nums[x] * nums[j] + burst(memo, nums, i, x) + burst(memo, nums, x, j));
}
memo[i][j] = max;
return max;
}
}