Skip to content

Commit 2e1bfe6

Browse files
committed
Add problem 312 - Burst Balloons
1 parent 771fd26 commit 2e1bfe6

File tree

2 files changed

+81
-0
lines changed

2 files changed

+81
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
from typing import List
2+
3+
4+
class BurstBalloons:
5+
@staticmethod
6+
def maxCoins(nums: List[int]) -> int:
7+
# Array of balloons with two dummy balloons
8+
balloons = [1] * (len(nums) + 2)
9+
n = len(balloons)
10+
for i in range(1, len(nums) + 1):
11+
balloons[i] = nums[i - 1]
12+
# Lookup table
13+
lookup = [[-1] * (n - 1) for _ in range(n - 1)]
14+
15+
def burst(balloons: List[int], i: int, j: int, lookup: List[List[int]]):
16+
# Base case
17+
if i > j:
18+
return 0
19+
# If there is only one balloon
20+
if i == j:
21+
temp = balloons[i]
22+
if i - 1 >= 0:
23+
temp *= balloons[i - 1]
24+
if j + 1 < len(balloons):
25+
temp *= balloons[j + 1]
26+
return temp
27+
28+
# If we have already calculated the result
29+
if lookup[i][j] != -1:
30+
return lookup[i][j]
31+
32+
# Score
33+
score = 0
34+
# We burst each balloon in the last in the range i to j
35+
for k in range(i, j + 1):
36+
# Burst the k-th balloon in the last after bursting balloons
37+
# in the range (i, k - 1) and (k + 1, j)
38+
temp = balloons[k]
39+
if i - 1 >= 0:
40+
temp *= balloons[i - 1]
41+
if j + 1 < len(balloons):
42+
temp *= balloons[j + 1]
43+
44+
# Recursively burst left and right halves
45+
temp += (burst(balloons, i, k - 1, lookup) + burst(balloons, k + 1, j, lookup))
46+
# Update score, if required
47+
score = max(score, temp)
48+
49+
lookup[i][j] = score
50+
return score
51+
52+
# Burst all balloons in the range 1, n - 2
53+
return burst(balloons, 1, n - 2, lookup)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import unittest
2+
3+
from problems.dynamic_programming.burst_balloons import BurstBalloons
4+
5+
6+
class TestBurstBalloons(unittest.TestCase):
7+
8+
def setUp(self):
9+
self.burst_balloons = BurstBalloons()
10+
11+
def test_max_coins_single_balloon(self):
12+
self.assertEqual(self.burst_balloons.maxCoins([5]), 5)
13+
14+
def test_max_coins_two_balloons(self):
15+
self.assertEqual(self.burst_balloons.maxCoins([3, 1]), 6)
16+
17+
def test_max_coins_multiple_balloons(self):
18+
self.assertEqual(self.burst_balloons.maxCoins([3, 1, 5, 8]), 167)
19+
20+
def test_max_coins_no_balloons(self):
21+
self.assertEqual(self.burst_balloons.maxCoins([]), 0)
22+
23+
def test_max_coins_large_case(self):
24+
self.assertEqual(self.burst_balloons.maxCoins([1, 2, 3, 4, 5, 6]), 252)
25+
26+
27+
if __name__ == '__main__':
28+
unittest.main()

0 commit comments

Comments
 (0)