-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBurstBalloons_312.cpp
81 lines (59 loc) · 1.94 KB
/
BurstBalloons_312.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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/*
~ Author : https://leetcode.com/tridib_2003/
~ Problem : 312. Burst Balloons
~ Link : https://leetcode.com/problems/burst-balloons/
*/
/* Approach 1 : Top-Down (Memoization) */
/*
class Solution {
public:
int maxCoinsUtil(vector<int> &nums, int l, int r, vector<vector<int> > &dp) {
if (l > r)
return 0;
if (dp[l][r] != -1)
return dp[l][r];
int maxCost = 0;
for (int i = l; i <= r; ++i) {
int currCost = (nums[l - 1] * nums[i] * nums[r + 1]) +
maxCoinsUtil(nums, l, i - 1, dp) + maxCoinsUtil(nums, i + 1, r, dp);
maxCost = max(maxCost, currCost);
}
return dp[l][r] = maxCost;
}
int maxCoins(vector<int>& nums) {
int n = nums.size();
nums.insert(nums.begin(), 1);
nums.emplace_back(1);
vector<vector<int> > dp(n + 1, vector<int> (n + 1, -1));
return maxCoinsUtil(nums, 1, n, dp);
}
};
*/
// Time Complexity - O(n^3)
// Auxiliary Space - O(n^2)
/* Approach 2 : Bottom-Up (Tabulation) */
class Solution {
public:
int maxCoins(vector<int>& nums) {
int n = nums.size();
nums.insert(nums.begin(), 1);
nums.emplace_back(1);
vector<vector<int> > dp(n + 2, vector<int> (n + 2, 0));
for (int i = n; i >= 1; --i) {
for (int j = 1; j <= n; ++j) {
if (i > j)
continue;
int maxCost = 0;
for (int idx = i; idx <= j; ++idx) {
int currCost = (nums[i - 1] * nums[idx] * nums[j + 1]) +
dp[i][idx - 1] + dp[idx + 1][j];
maxCost = max(maxCost, currCost);
}
dp[i][j] = maxCost;
}
}
return dp[1][n];
}
};
// Time Complexity - O(n^3)
// Auxiliary Space - O(n^2)