Leetcode 312 Solution

This article provides solution to leetcode question 312 (burst-balloons)

https://leetcode.com/problems/burst-balloons

Solution

class Solution {
public:
    int maxCoins(vector<int>& nums) {
        int n = nums.size();

        if (n == 0)
            return 0;

        nums.insert(nums.begin(), 1);
        nums.push_back(1);

        int dp[n + 2][n + 2];

        for (int i = 0; i < n + 2; i++)
            for (int j = 0; j < n + 2; j++)
                dp[i][j] = 0;

        for (int d = 0; d < n; d++)
        {
            for (int i = 1; i + d <= n; i++)
            {
                int j = i + d;

                for (int k = i; k <= j; k++)
                    dp[i][j] = max(dp[i][j], nums[i - 1] * nums[k] * nums[j + 1] + dp[i][k - 1] + dp[k + 1][j]);
            }
        }

        return dp[1][n];
    }
};