|
| 1 | +from typing import List |
| 2 | + |
| 3 | + |
| 4 | +class BurstBalloons: |
| 5 | + @staticmethod |
| 6 | + def maxCoins(nums: List[int]) -> int: |
| 7 | + # Array of balloons with two dummy balloons |
| 8 | + balloons = [1] * (len(nums) + 2) |
| 9 | + n = len(balloons) |
| 10 | + for i in range(1, len(nums) + 1): |
| 11 | + balloons[i] = nums[i - 1] |
| 12 | + # Lookup table |
| 13 | + lookup = [[-1] * (n - 1) for _ in range(n - 1)] |
| 14 | + |
| 15 | + def burst(balloons: List[int], i: int, j: int, lookup: List[List[int]]): |
| 16 | + # Base case |
| 17 | + if i > j: |
| 18 | + return 0 |
| 19 | + # If there is only one balloon |
| 20 | + if i == j: |
| 21 | + temp = balloons[i] |
| 22 | + if i - 1 >= 0: |
| 23 | + temp *= balloons[i - 1] |
| 24 | + if j + 1 < len(balloons): |
| 25 | + temp *= balloons[j + 1] |
| 26 | + return temp |
| 27 | + |
| 28 | + # If we have already calculated the result |
| 29 | + if lookup[i][j] != -1: |
| 30 | + return lookup[i][j] |
| 31 | + |
| 32 | + # Score |
| 33 | + score = 0 |
| 34 | + # We burst each balloon in the last in the range i to j |
| 35 | + for k in range(i, j + 1): |
| 36 | + # Burst the k-th balloon in the last after bursting balloons |
| 37 | + # in the range (i, k - 1) and (k + 1, j) |
| 38 | + temp = balloons[k] |
| 39 | + if i - 1 >= 0: |
| 40 | + temp *= balloons[i - 1] |
| 41 | + if j + 1 < len(balloons): |
| 42 | + temp *= balloons[j + 1] |
| 43 | + |
| 44 | + # Recursively burst left and right halves |
| 45 | + temp += (burst(balloons, i, k - 1, lookup) + burst(balloons, k + 1, j, lookup)) |
| 46 | + # Update score, if required |
| 47 | + score = max(score, temp) |
| 48 | + |
| 49 | + lookup[i][j] = score |
| 50 | + return score |
| 51 | + |
| 52 | + # Burst all balloons in the range 1, n - 2 |
| 53 | + return burst(balloons, 1, n - 2, lookup) |
0 commit comments