Skip to content

Commit 03a55d8

Browse files
authored
Create Burst Balloons.py
1 parent 6c3c6e9 commit 03a55d8

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

Burst Balloons.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
'''
2+
Given n balloons, indexed from 0 to n-1. Each balloon is painted with a number on it represented by array nums. You are asked to burst all the balloons. If the you burst balloon i you will get nums[left] * nums[i] * nums[right] coins. Here left and right are adjacent indices of i. After the burst, the left and right then becomes adjacent.
3+
4+
Find the maximum coins you can collect by bursting the balloons wisely.
5+
6+
Note:
7+
8+
You may imagine nums[-1] = nums[n] = 1. They are not real therefore you can not burst them.
9+
0 ≤ n ≤ 500, 0 ≤ nums[i] ≤ 100
10+
Example:
11+
12+
Input: [3,1,5,8]
13+
Output: 167
14+
Explanation: nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> []
15+
coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167
16+
'''
17+
18+
19+
class Solution(object):
20+
def maxCoins(self, nums):
21+
"""
22+
:type nums: List[int]
23+
:rtype: int
24+
"""
25+
nums = [1] + nums + [1]
26+
n = len(nums)
27+
dp = [[0 for j in xrange(n)] for i in xrange(n)]
28+
29+
for gap in xrange(2, n):
30+
for i in xrange(n - gap):
31+
j = i + gap
32+
for k in xrange(i+1, j):
33+
dp[i][j] = max(dp[i][j], dp[i][k] + dp[k][j] + nums[i] * nums[k] * nums[j])
34+
35+
return dp[0][n-1]

0 commit comments

Comments
 (0)