Skip to content

Commit 0ed3cc4

Browse files
Merge pull request #289 from AnishTiwari16/anish/burstBalloons
added burst balloons problem on DP
2 parents ee17dcc + c7662e3 commit 0ed3cc4

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

Dynamic Programming/burstBalloons.cpp

+56
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
// this is hard level DP problem on lc
2+
// https://leetcode.com/problems/burst-balloons/
3+
4+
// both memoization and tabulation approaches
5+
class Solution
6+
{
7+
// private:
8+
// int solve(int i, int j, vector<int>&nums,vector<vector<int>>&dp){
9+
// //base case
10+
// if(i>j){
11+
// return 0;
12+
// }
13+
// if(dp[i][j]!=-1){
14+
// return dp[i][j];
15+
// }
16+
// int ans = INT_MIN;
17+
// for(int ind = i;ind<=j;ind++){
18+
// //think in terms as we are bursting last balloon
19+
// int cost = nums[ind]*nums[i-1]*nums[j+1] + solve(i,ind-1,nums,dp) + solve(ind+1,j,nums,dp);
20+
// ans = max(ans,cost);
21+
// }
22+
// return dp[i][j] = ans;
23+
// }
24+
public:
25+
int maxCoins(vector<int> &nums)
26+
{
27+
// mcm as we are given according to ordering and maxi so use dp
28+
nums.push_back(1);
29+
nums.insert(nums.begin(), 1);
30+
//[1,3,1,5,8,1]
31+
int n = nums.size();
32+
// vector<vector<int>>dp(n,vector<int>(n,-1));
33+
// return solve(1,n-2,nums,dp);
34+
vector<vector<int>> dp(n + 2, vector<int>(n + 2, 0));
35+
36+
// think in terms of reverse of memo
37+
for (int i = n - 2; i >= 1; i--)
38+
{
39+
for (int j = 1; j <= n - 2; j++)
40+
{
41+
if (i > j)
42+
{
43+
continue;
44+
}
45+
int ans = INT_MIN;
46+
for (int ind = i; ind <= j; ind++)
47+
{
48+
int cost = nums[ind] * nums[i - 1] * nums[j + 1] + dp[i][ind - 1] + dp[ind + 1][j];
49+
ans = max(ans, cost);
50+
}
51+
dp[i][j] = ans;
52+
}
53+
}
54+
return dp[1][n - 2];
55+
}
56+
};

0 commit comments

Comments
 (0)