Skip to content

Commit 701fb63

Browse files
committed
Create burst-balloons.py
1 parent 9630088 commit 701fb63

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

Python/burst-balloons.py

+52
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
# Time: O(n^3)
2+
# Space: O(n^2)
3+
4+
# Given n balloons, indexed from 0 to n-1.
5+
# Each balloon is painted with a number on it
6+
# represented by array nums.
7+
# You are asked to burst all the balloons.
8+
# If the you burst balloon i you will get
9+
# nums[left] * nums[i] * nums[right] coins.
10+
# Here left and right are adjacent indices of i.
11+
# After the burst, the left and right then
12+
# becomes adjacent.
13+
#
14+
# Find the maximum coins you can collect by
15+
# bursting the balloons wisely.
16+
#
17+
# Note:
18+
# (1) You may imagine nums[-1] = nums[n] = 1.
19+
# They are not real therefore you can not burst them.
20+
# (2) 0 <= n <= 500, 0 <= nums[i] <= 100
21+
#
22+
# Example:
23+
#
24+
# Given [3, 1, 5, 8]
25+
#
26+
# Return 167
27+
#
28+
# nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> []
29+
# coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167
30+
#
31+
32+
# TLE, although it could pass in C++.
33+
class Solution(object):
34+
def maxCoins(self, nums):
35+
"""
36+
:type nums: List[int]
37+
:rtype: int
38+
"""
39+
coins = [1] + [i for i in nums if i > 0] + [1]
40+
n = len(coins)
41+
max_coins = [[0 for _ in xrange(n)] for _ in xrange(n)]
42+
43+
for k in xrange(2, n):
44+
for left in xrange(n - k):
45+
right = left + k
46+
for i in xrange(left + 1, right):
47+
max_coins[left][right] = max(max_coins[left][right], \
48+
coins[left] * coins[i] * coins[right] + \
49+
max_coins[left][i] + max_coins[i][right])
50+
51+
return max_coins[0][-1]
52+

0 commit comments

Comments
 (0)