Skip to content

Commit 680a0ce

Browse files
author
Alex Syrotenko
committed
Add Burst Baloons DP problem solution
1 parent 9ac05d1 commit 680a0ce

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
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+
}

0 commit comments

Comments
 (0)