2
\$\begingroup\$

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]   -->  [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 = [1] + nums + [1]
    n = len(nums)
    dp = [[0] * 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[0][-1]

Here is the Leetcode result (70 test cases) -

enter image description here

So, I would like to know whether I could make this program shorter and more efficient.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.