Burst Balloons in C++



Suppose we have n balloons, these are indexed from 0 to n-1. Here each balloon is painted with a number on it represented by one array called nums. we have to burst all the balloons. If we burst balloon i we will get nums[i – 1] * nums[i] * nums[i + 1] number of coins. After the burst, the i – 1 and i + 1 then becomes adjacent. We have to find the maximum coins to collect by bursting the balloons wisely.

So if the input is like [3,1,5,7], then the result will be 148. Initially the array is like [3,1,5,7], then after bursting 1, we will get 3 * 1 * 5 = 15, then the array is [3,5,7], then burst 5, so we will get (3 * 5 * 7) = 105, then array is like [3,7], then burst 3, so we will get (1*3*7) = 21, finally the array is [7], so after bursting, we will get 7, so the total is 15 + 105 + 21 + 7 = 148.

To solve this, we will follow these steps −

  • n := size of a

  • if (n is non-zero) is false, then,

    • return 0

  • Define one 2D array dp of order n x n

  • for initializing l := n - 1, when l >= 0, decrease l by 1 do −

    • for initializing r := l, when r < n, increase r by 1 do −

      • for initializing i := l, when i <= r, increase i by 1 do −

        • y := dp[i + 1, r] if i + 1 < n, otherwise 0

        • z := a[l - 1] if l - 1 >= 0 otherwise 1

        • w := a[r + 1] if r + 1 < n otherwise 1

        • x := dp[l, i - 1] if i - 1 > = 0, otherwise 0 + y + (z * w * a[i])

        • dp[l, r] := max of dp[l, r] and x

  • return dp[0, n - 1]

Example

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int maxCoins(vector<int>& a) {
      int n = a.size();
      if(!n)return 0;
      vector < vector <int>> dp(n,vector <int> (n));
      for(int l = n-1;l>=0;l--){
         for(int r=l;r<n;r++){
            for(int i =l;i<=r;i++){
               dp[l][r] = max(dp[l][r],(i-1>=0?dp[l][i-1]:0) +(i+1<n?dp[i+1][r]:0)+((l-1>=0?a[l-1]:1 )*(r+1<n?a[r+1]:1)*a[i]));
            }
         }
      }
      return dp[0][n-1];
   }
};
main(){
   Solution ob;
   vector<int> v = {3,1,5,7};
   cout << (ob.maxCoins(v));
}

Input

[3,1,5,7]

Output

148

Advertisements