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
Solution
public class Solution {
int[][] memory;
public int maxCoins(int[] nums) {
memory = new int[nums.length][nums.length];
for(int i = 0; i < nums.length; i++)
for(int j = 0; j < nums.length; j++)
memory[i][j] = -1;
return burst(nums, 0, nums.length-1);
}
public int burst(int[] nums, int i, int j) {
if(i > j) return 0;
if(memory[i][j] != -1) return memory[i][j];
// memorized dfs
int max = 0;
int left = i == 0 ? 1 : nums[i - 1];
int right = j == nums.length - 1 ? 1 : nums[j + 1];
for(int last = i; last <= j; last++) {
int coins = nums[last] * left * right + burst(nums, i, last-1) + burst(nums, last+1, j);
max = Integer.max(coins, max);
}
memory[i][j] = max;
return max;
}
}