Skip to content

Commit e21a900

Browse files
Added Burst_Balloons.cpp
1 parent 4ba4158 commit e21a900

1 file changed

Lines changed: 77 additions & 0 deletions

File tree

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
/*
2+
* Burst Balloons (Dynamic Programming)
3+
*
4+
* Description:
5+
* You are given n balloons, each balloon has a number on it represented by an array nums[].
6+
* When you burst a balloon i, you gain coins equal to:
7+
* nums[left] * nums[i] * nums[right]
8+
* where left and right are the adjacent balloons still remaining.
9+
* After bursting, balloon i is removed and the array shrinks.
10+
* Return the maximum coins you can collect by bursting balloons wisely.
11+
*
12+
* Approach:
13+
* - Add virtual balloons with value 1 at both ends for easier handling.
14+
* - Use Dynamic Programming (DP) on intervals.
15+
* dp[i][j] = maximum coins obtainable by bursting balloons between index i and j (exclusive).
16+
* - For each range (i, j), consider every balloon k between i and j as the last balloon to burst:
17+
* dp[i][j] = max(dp[i][j], nums[i]*nums[k]*nums[j] + dp[i][k] + dp[k][j])
18+
* - Final answer = dp[0][n-1]
19+
*
20+
* Time Complexity: O(n^3)
21+
* Space Complexity: O(n^2)
22+
*/
23+
24+
#include <bits/stdc++.h>
25+
using namespace std;
26+
27+
class Solution {
28+
public:
29+
int maxCoins(vector<int>& nums) {
30+
int n = nums.size();
31+
nums.insert(nums.begin(), 1);
32+
nums.push_back(1);
33+
vector<vector<int>> dp(n + 2, vector<int>(n + 2, 0));
34+
35+
// len is the distance between i and j
36+
for (int len = 2; len < n + 2; len++) {
37+
for (int i = 0; i + len < n + 2; i++) {
38+
int j = i + len;
39+
for (int k = i + 1; k < j; k++) {
40+
dp[i][j] = max(dp[i][j], nums[i]*nums[k]*nums[j] + dp[i][k] + dp[k][j]);
41+
}
42+
}
43+
}
44+
45+
return dp[0][n + 1];
46+
}
47+
};
48+
49+
int main() {
50+
Solution sol;
51+
52+
// Test Case 1
53+
cout << "Test Case 1:" << endl;
54+
vector<int> nums1 = {3, 1, 5, 8};
55+
cout << "Balloons: [3, 1, 5, 8]" << endl;
56+
cout << "Max Coins: " << sol.maxCoins(nums1) << endl << endl; // 167
57+
58+
// Test Case 2
59+
cout << "Test Case 2:" << endl;
60+
vector<int> nums2 = {1, 5};
61+
cout << "Balloons: [1, 5]" << endl;
62+
cout << "Max Coins: " << sol.maxCoins(nums2) << endl << endl; // 10
63+
64+
// Test Case 3
65+
cout << "Test Case 3:" << endl;
66+
vector<int> nums3 = {9, 76, 64, 21};
67+
cout << "Balloons: [9, 76, 64, 21]" << endl;
68+
cout << "Max Coins: " << sol.maxCoins(nums3) << endl << endl;
69+
70+
// Test Case 4 (Single balloon)
71+
cout << "Test Case 4:" << endl;
72+
vector<int> nums4 = {7};
73+
cout << "Balloons: [7]" << endl;
74+
cout << "Max Coins: " << sol.maxCoins(nums4) << endl << endl; // 7
75+
76+
return 0;
77+
}

0 commit comments

Comments
 (0)