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

1
2
nums = [3,1,5,8] --> [3,5,8] -->   [3,8]   -->  [8]  --> []
coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167

O(n^3) time O(n^2) space DP solution

Derivation of DP transformation equation

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
public class Solution {
public int maxCoins(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int[] coin = new int[nums.length + 2];
int n = 1;
for (int num : nums) {
if (num > 0) {
coin[n++] = num;
}
}
coin[0] = coin[n++] = 1;

int[][] maxCoins = new int[n][n];
for (int k = 2; k < n; k++) {
for (int left = 0; left < n - k; left++) {
int right = left + k;
for (int i = left + 1; i < right; i++) {
maxCoins[left][right] = Math.max(maxCoins[left][right], coin[left] * coin[i] * coin[right] + maxCoins[left][i] + maxCoins[i][right]);
}
}
}
return maxCoins[0][n - 1];
}
}

Divide and conquer solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// divide and conquer
int maxCoins1(vector<int>& nums) {
int n = nums.size();
nums.insert(nums.begin(), 1);
nums.insert(nums.end(), 1);
vector<vector<int> > dp(n+2, vector<int>(n+2, 0));
return DP(1, n, nums, dp);
}

// remember search
int DP(int i, int j, const vector<int> &nums, vector<vector<int>> &dp) {
if (dp[i][j] > 0) return dp[i][j];
for (int x = i; x <= j; ++x) {
int temp = DP(i, x-1, nums, dp) + nums[i-1]*nums[x]*nums[j+1] + DP(x+1, j, nums, dp);
if (temp > dp[i][j]) dp[i][j] = temp;
}
return dp[i][j];
}