File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed
Dynamic Programming/Burst_Baloons Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change 1+ // Problem statement :
2+ // Given n balloons, indexed from 0 to n-1.
3+ // Each balloon is painted with a number on it represented by array nums.
4+ // You are asked to burst all the balloons.
5+ // If the you burst balloon i you will get nums[left] * nums[i] * nums[right] coins.
6+ // Here left and right are adjacent indices of i.
7+ // After the burst, the left and right then becomes adjacent.
8+ #include < vector>
9+ #include < assert.h>
10+
11+ int burst_baloons (const std::vector<int > baloons) {
12+ int *nums = new int [baloons.size () + 2 ];
13+ int n = 1 ;
14+ for (int x : baloons)
15+ if (x > 0 )
16+ nums[n++] = x;
17+ nums[0 ] = nums[n++] = 1 ;
18+
19+ int **dp = new int *[n];
20+ for (int i = 0 ; i < n; ++i)
21+ dp[i] = new int [n];
22+ for (int k = 2 ; k < n; ++k)
23+ for (int left = 0 ; left < n - k; ++left) {
24+ int right = left + k;
25+ for (int i = left + 1 ; i < right; ++i) {
26+ int challenger = nums[left] * nums[i] * nums[right] + dp[left][i] + dp[i][right];
27+ dp[left][right] = std::max (dp[left][right], challenger);
28+ }
29+ }
30+
31+ return dp[0 ][n - 1 ];
32+ }
33+
34+ int main () {
35+ const std::vector<int > input {3 , 1 , 5 , 8 };
36+ int result = burst_baloons (input);
37+ assert (result == 167 );
38+ return 0 ;
39+ }
You can’t perform that action at this time.
0 commit comments