Search code examples
pythonalgorithmrecursionmemoization

Bursting baloon is timing out in leetcode


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.

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

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

I am getting time out for some of the test cases.

Wondering how to improve? Please just give me hints only.

class Solution(object):
        def recursion(self, nums, index, dp):
            r = -1
            if not nums:
                return 0
            if len(nums) == 1:
                return nums[0]
            if str(nums) in dp:
                return dp[str(nums)]
            if index >= len(nums):
                return 0
            for i in range(len(nums)):
                if i == 0:
                    r = max(r, nums[i]*nums[i+1] + self.recursion(nums[0:i]+nums[i+1:][:], i, dp))
                elif i == len(nums)-1:
                    r = max(r, nums[i-1]*nums[i] + self.recursion(nums[0:i]+nums[i+1:][:], i, dp))
                else:
                    r = max(r, nums[i-1]*nums[i]*nums[i+1] + self.recursion(nums[0:i]+nums[i+1:][:], i, dp))
            dp[str(nums)] = r
            return r

        def maxCoins(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            return self.recursion(nums, 0, {})

Solution

  • Hint: try to avoid copying the list in each recursion.

    p.s.: I'm pretty sure there's a dynamic programming solution that has a time complexity of O(n^3).