Burst Balloons
Given n balloons, indexed from 0 to n-1. Each balloon is painted with a
number on it represented by array nums.
You are asked to burst all the balloons. If the you burst
balloon i you will get nums[left] * nums[i] * nums[right] coins. Here left
and right are adjacent indices of i. After the burst, the left and right
then becomes adjacent.
Find the maximum coins you can collect by bursting the balloons wisely.
Note:
(1) You may imagine nums[-1] = nums[n] = 1. They are not real therefore you can not burst them.
(2) 0 ≤ n ≤ 500, 0 ≤ nums[i] ≤ 100
Example:
Given [3, 1, 5, 8]
Return 167
nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> []
coins = 315 + 358 + 138 + 181 = 167
Credits:Special thanks to @dietpepsi for adding this problem and creating all test cases.
Solution
public class Solution {
public int maxCoins(int[] nums) {
if (nums == null || nums.length == 0) return 0;
if (nums.length == 1) return nums[0];
int[] newArray = new int[nums.length + 2];
newArray[0] = 1;
newArray[newArray.length - 1] = 1;
for (int i = 0; i < nums.length; i++) {
newArray[i + 1] = nums[i];
}
nums = newArray;
int[][] memory = new int[nums.length][nums.length];
int result = get(memory, nums, 0, nums.length - 1);
return result;
}
private int get(int[][] memory, int[] nums, int start, int end) {
if (start + 1 >= end) return 0;
if (memory[start][end] != 0) return memory[start][end];
int max = Integer.MIN_VALUE;
for (int i = start + 1; i < end; i++) {
int tempt = getValue(nums, start) * getValue(nums, i) * getValue(nums, end) + get(memory, nums, start, i) + get(memory, nums, i, end);
max = Math.max(max, tempt);
}
memory[start][end] = max;
return max;
}
private int getValue(int[] nums, int index) {
if (index == -1) return 1;
if (index == nums.length) return 1;
return nums[index];
}
}