Problem Statement

You are given n balloons, indexed from 0 to n - 1. Each balloon is painted with a number on it represented by an array nums. You are asked to burst all the balloons.

If you burst the ith balloon, you will get nums[i - 1] * nums[i] * nums[i + 1] coins. If i - 1 or i + 1 goes out of bounds of the array, then treat it as if there is a balloon with a 1 painted on it.

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

Example 1:

Input: nums = [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

Reference Video

https://www.youtube.com/watch?v=uG_MtaCJIrM&ab_channel=TECHDOSE

Code

class Solution {
public:
    int maxCoins(vector<int>& nums) {
        
        int n = nums.size();
        
        int b[n+2];
        
        b[0] = 1;
        b[n+1] = 1;
        
        for(int i=1;i<=n;i++)
            b[i] = nums[i-1];
        
        vector <vector<int>> dp(n+2,vector<int>(n+2,0));
        
        for(int w=1;w<=n;w++)
        {
            for(int left=1;left<=n-w+1;left++)
            {
                int right = left+w-1;
                for(int i=left;i<=right;i++)
                {
                    int cost = b[left-1] * b[i] * b[right+1] + dp[i+1][right] + 
										dp[left][i-1];
                    dp[left][right] = max( dp[left][right], cost );
                }
            }
        }
            return dp[1][n];
        
    }
};
// Time Complexity : O(n^3)
// Space Complexity : O(n^2)