-
Notifications
You must be signed in to change notification settings - Fork 258
/
Copy pathburst-balloons.cpp
33 lines (30 loc) · 992 Bytes
/
burst-balloons.cpp
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
27
28
29
30
31
32
33
// Time: O(n^3)
// Space: O(n^2)
class Solution {
public:
/**
* @param nums a list of integer
* @return an integer, maximum coins
*/
int maxCoins(vector<int>& nums) {
vector<int> coins;
coins.emplace_back(1);
for (const auto& n : nums) {
if (n > 0) {
coins.emplace_back(n);
}
}
coins.emplace_back(1);
vector<vector<int>> max_coins(coins.size(), vector<int>(coins.size()));
for (int k = 2; k < coins.size(); ++k) {
for (int left = 0; left < coins.size() - k; ++left) {
for (int i = left + 1, right = left + k; i < right; ++i) {
max_coins[left][right] = max(max_coins[left][right],
coins[left] * coins[i] * coins[right] +
max_coins[left][i] + max_coins[i][right]);
}
}
}
return max_coins[0][coins.size() - 1];
}
};