|
1 | 1 | package com.fishercoder.solutions;
|
2 | 2 |
|
3 | 3 | /**
|
4 |
| - * 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. |
| 4 | + * 312. Burst Balloons |
| 5 | + * |
| 6 | + * Given n balloons, indexed from 0 to n-1. |
| 7 | + * Each balloon is painted with a number on it represented by array nums. |
| 8 | + * You are asked to burst all the balloons. |
| 9 | + * If the you burst balloon i you will get nums[left] * nums[i] * nums[right] coins. |
| 10 | + * Here left and right are adjacent indices of i. After the burst, the left and right then becomes adjacent. |
5 | 11 |
|
6 | 12 | Find the maximum coins you can collect by bursting the balloons wisely.
|
7 | 13 |
|
|
20 | 26 | */
|
21 | 27 | public class _312 {
|
22 | 28 |
|
23 |
| - public int maxCoins(int[] iNums) { |
24 |
| - int[] nums = new int[iNums.length + 2]; |
25 |
| - int n = 1; |
26 |
| - for (int x : iNums) { |
27 |
| - if (x > 0) { |
28 |
| - nums[n++] = x; |
| 29 | + public static class Solution1 { |
| 30 | + public int maxCoins(int[] iNums) { |
| 31 | + int[] nums = new int[iNums.length + 2]; |
| 32 | + int n = 1; |
| 33 | + for (int x : iNums) { |
| 34 | + if (x > 0) { |
| 35 | + nums[n++] = x; |
| 36 | + } |
29 | 37 | }
|
30 |
| - } |
31 |
| - nums[0] = nums[n++] = 1; |
32 |
| - |
33 |
| - |
34 |
| - int[][] dp = new int[n][n]; |
35 |
| - for (int k = 2; k < n; ++k) { |
36 |
| - for (int left = 0; left < n - k; ++left) { |
37 |
| - int right = left + k; |
38 |
| - for (int i = left + 1; i < right; ++i) { |
39 |
| - dp[left][right] = Math.max(dp[left][right], |
| 38 | + nums[0] = nums[n++] = 1; |
| 39 | + |
| 40 | + int[][] dp = new int[n][n]; |
| 41 | + for (int k = 2; k < n; ++k) { |
| 42 | + for (int left = 0; left < n - k; ++left) { |
| 43 | + int right = left + k; |
| 44 | + for (int i = left + 1; i < right; ++i) { |
| 45 | + dp[left][right] = Math.max(dp[left][right], |
40 | 46 | nums[left] * nums[i] * nums[right] + dp[left][i] + dp[i][right]);
|
| 47 | + } |
41 | 48 | }
|
42 | 49 | }
|
| 50 | + return dp[0][n - 1]; |
43 | 51 | }
|
44 |
| - return dp[0][n - 1]; |
45 | 52 | }
|
46 |
| - |
47 | 53 | }
|
0 commit comments