# Bursting Balloons

This is a Leetcode problem -

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 you burst the 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 become adjacent.

Find the maximum coins you can collect by bursting the balloons wisely.

Note -

• You may imagine nums[-1] = nums[n] = 1. They are not real, therefore, you can not burst them.
• $$\0\$$ $$\≤\$$ n $$\≤\$$ $$\500\$$$$\,\$$ $$\0\$$ $$\≤\$$ nums[i] $$\≤\$$ $$\100\$$

Example -

Input: [3,1,5,8]

Output: 167

Explanation: nums = [3,1,5,8] --> [3,5,8] -->   [3,8]   -->    --> []
coins =   3*1*5     +  3*5*8    +   1*3*8     + 1*8*1   = 167


Here is my solution to this challenge -

# Uses dynamic programming

def max_coins(nums):
"""
:type nums: List[int]
:rtype: int
"""
nums =  + nums + 
n = len(nums)
dp = [ * n for i in range(n)]
for j in range(2, n):
for i in range(j - 2, -1, -1):
for k in range(i + 1,j):
dp[i][j] = max(dp[i][j], dp[i][k] + dp[k][j] + nums[i] * nums[j] * nums[k])
return dp[-1]


Here is the Leetcode result (70 test cases) - So, I would like to know whether I could make this program shorter and more efficient.

• Is code length your primary concern? If I see that code, eliminating the doubly nested for-loop would be mine. – Mast Jun 3 '19 at 12:36
• Well, my main concern is efficiency and it would just be better if it could be made shorter. – Justin Jun 3 '19 at 12:58
• Small things dp = [ * n for i in range(n)] can be dp = [ * n for _ in range(n)]. By convention in python if we dont use the index variable we just use _ – Mitchel Paulin Jun 5 '19 at 14:34