312 Burst Balloons
312. Burst Balloons
1. Question
nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] -->[]
coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 1672. Implementation
class Solution {
public int maxCoins(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int n = nums.length;
// Add 2 because we wanna include the boundary nums[-1] and nums[n]
int[] coins = new int[n + 2];
coins[0] = 1;
coins[n + 1] = 1;
for (int i = 1; i <= n; i++) {
coins[i] = nums[i - 1];
}
// 我们要找的答案在dp[1][n]
// dp[i][j] means the max coins we can collect in the coin(i..j)
int[][] dp = new int[n + 2][n + 2];
for (int len = 1; len <= n; len++) {
for (int start = 1; start <= n - len + 1; start++) {
int end = start + len - 1;
for (int mid = start; mid <= end; mid++) {
dp[start][end] = Math.max(dp[start][end], dp[start][mid - 1] + dp[mid + 1][end] + coins[start - 1] * coins[mid] * coins[end + 1]);
}
}
}
return dp[1][n];
}
}3. Time & Space Complexity
Last updated