The Wayback Machine - https://web.archive.org/web/20250114132316/https://www.geeksforgeeks.org/burst-balloon-to-maximize-coins/
Open In App

Burst Balloon to maximize coins

Last Updated : 09 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given n balloons indexed from 0 to n – 1, each with some coins associated with it represented by an array arr[]. On bursting balloon i, the number of coins gained is equal to arr[i-1]* arr[i]* arr[i+1]. If i – 1 or i + 1 goes out of bounds of the arr[], then assumes an extra 1 at each boundary. Find the maximum possible profit earned after bursting all the balloons.

Examples :

Input: arr[] = [5, 10]
Output: 60
Explanation –
arr = [5, 10] –> [10] –> []
coins = 1*5*10 + 1*10*1 = 60

Input: arr[] = [3, 1, 5, 8]
Output: 167
Explanation:
arr = [3, 1, 5, 8] –> [3, 5, 8] –> [3, 8] –> [8] –> []
coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167

Using recursion

To solve the balloon-bursting problem using recursion, let’s consider a recursive approach by focusing on each balloon burst individually and calculating the maximum profit at each step.

To maximize the profit from bursting balloons, we can choose a balloon i to burst last in a range [left, right]. The profit from bursting i last is given by arr[left-1] * arr[i] * arr[right+1], plus the maximum profit from the left subarray [left, i-1] and right subarray [i+1, right].

This gives the recurrence relation:

  • maxCoins(l, r) = max(arr[l-1] * arr[i] * arr[r+1] + maxCoins(l, i-1) + maxCoins(i+1, r))
C++
// C++ code of getting maximum value 
// by bursting Balloons using recursion.

#include <bits/stdc++.h>
using namespace std;

// Recursive function to calculate maximum 
// coins from bursting balloons in range [left, right]
int getMaxCoins(int left, int right, vector<int> &arr) {
  
      // No balloons in this range
    if (left > right) return 0; 

    int maxCoins = 0;

    // Try each balloon `k` in range [left, right] 
      // as the last balloon to burst
    for (int k = left; k <= right; k++) {
          
        // Calculate coins from bursting `k` 
          // last in this range
        int coins = arr[left - 1] * arr[k] * arr[right + 1];

        // Recursively compute coins from the left and 
          // right subarrays
        int leftCoins = getMaxCoins(left, k - 1, arr);
        int rightCoins = getMaxCoins(k + 1, right, arr);

        // Update maxCoins with the best option
        maxCoins = max(maxCoins, coins + leftCoins + rightCoins);
    }
    
    return maxCoins;
}

// Function to calculate the maximum coins
// obtainable by bursting all balloons
int maxCoins(vector<int> &arr) {
  
      int n = arr.size();
  
    // Add virtual balloons with value 
      // 1 at both ends of `nums`
    arr.insert(arr.begin(), 1);
    arr.push_back(1);

    // Call recursive helper on the 
      // full range of balloons
    return getMaxCoins(1, n, arr);
}

int main() {
  
    vector<int> arr = {3, 1, 5, 8};
    cout << maxCoins(arr);
    return 0;
}
Java
// Java code of getting maximum value
// by bursting Balloons using recursion.
import java.util.*;

class GfG {

    // Recursive function to calculate maximum coins from
    // bursting balloons in range [left, right]
    static int getMaxCoins(int left, int right, int[] arr) {

        // No balloons in this range
        if (left > right)
            return 0;

        int maxCoins = 0;

        // Try each balloon `k` in range [left, right] as
        // the last balloon to burst
        for (int k = left; k <= right; k++) {

            // Calculate coins from bursting `k` last in
            // this range
            int coins
                = arr[left - 1] * arr[k] * arr[right + 1];

            // Recursively compute coins from the left and
            // right subarrays
            int leftCoins = getMaxCoins(left, k - 1, arr);
            int rightCoins = getMaxCoins(k + 1, right, arr);

            // Update maxCoins with the best option
            maxCoins = Math.max(maxCoins, coins + leftCoins
                                              + rightCoins);
        }

        return maxCoins;
    }

    // Function to calculate the maximum coins obtainable by
    // bursting all balloons
    static int maxCoins(int[] arr) {
      
        int n = arr.length;

        // Create a new array to store the original array
        // plus virtual balloons at the ends
        int[] nums = new int[n + 2];

        // Add virtual balloons with value 1 
          // at both ends of `nums`
        nums[0] = 1;
        nums[n + 1] = 1;

        // Copy the elements of the original array into the
        // new array
        for (int i = 0; i < n; i++) {
            nums[i + 1] = arr[i];
        }

        // Call recursive helper on the full range of
        // balloons
        return getMaxCoins(1, n, nums);
    }

    public static void main(String[] args) {
      
        int[] arr = { 3, 1, 5, 8 };
        System.out.println(
            maxCoins(arr));
    }
}
Python
# Python code of getting maximum value 
# by bursting Balloons using recursion.

# Recursive function to calculate maximum coins
# from bursting balloons in range [left, right]
def get_max_coins(left, right, arr):
  
    # No balloons in this range
    if left > right:
        return 0

    max_coins = 0

    # Try each balloon `k` in range [left, right] 
    # as the last balloon to burst
    for k in range(left, right + 1):
      
        # Calculate coins from bursting `k` last in this range
        coins = arr[left - 1] * arr[k] * arr[right + 1]

        # Recursively compute coins from the left and
        # right subarrays
        left_coins = get_max_coins(left, k - 1, arr)
        right_coins = get_max_coins(k + 1, right, arr)

        # Update max_coins with the best option
        max_coins = max(max_coins, coins + left_coins + right_coins)

    return max_coins

# Function to calculate the maximum coins
# obtainable by bursting all balloons
def max_coins(arr):
  
    # Add virtual balloons with value 1 at both
    # ends of `nums`
    n = len(arr)
    arr = [1] + arr + [1]

    # Call recursive helper on the full 
    # range of balloons
    return get_max_coins(1, n, arr)

arr = [3, 1, 5, 8]
print(max_coins(arr))
C#
// C# code of getting maximum value 
// by bursting Balloons using recursion.
using System;
using System.Collections.Generic;

class GfG {
  
    // Recursive function to calculate maximum 
    // coins from bursting balloons in range [left, right]
    static int GetMaxCoins(int left, int right, List<int> arr) {
      
        // No balloons in this range
        if (left > right) return 0;

        int maxCoins = 0;

        // Try each balloon `k` in range [left, right] 
        // as the last balloon to burst
        for (int k = left; k <= right; k++) {
          
            // Calculate coins from bursting `k` last in this range
            int coins = arr[left - 1] * arr[k] * arr[right + 1];

            // Recursively compute coins from the left 
              // and right subarrays
            int leftCoins = GetMaxCoins(left, k - 1, arr);
            int rightCoins = GetMaxCoins(k + 1, right, arr);

            // Update maxCoins with the best option
            maxCoins = Math.Max(maxCoins, coins + leftCoins
                                + rightCoins);
        }

        return maxCoins;
    }

    // Function to calculate the maximum coins
    // obtainable by bursting all balloons
    static int MaxCoins(List<int> arr) {
      
        // Add virtual balloons with value 
          // 1 at both ends of `nums`
           int n = arr.Count;
        arr.Insert(0, 1);
        arr.Add(1);

        // Call recursive helper on the full range
          // of balloons
        return GetMaxCoins(1, n, arr);
    }

    static void Main() {
      
        List<int> arr = new List<int> { 3, 1, 5, 8 };
        Console.WriteLine(MaxCoins(arr));
    }
}
JavaScript
// JavaScript code of getting maximum value 
// by bursting Balloons using recursion.

// Recursive function to calculate maximum coins
// from bursting balloons in range [left, right]
function getMaxCoins(left, right, arr) {

    // No balloons in this range
    if (left > right)
        return 0;

    let maxCoins = 0;

    // Try each balloon `k` in range [left, right]
    // as the last balloon to burst
    for (let k = left; k <= right; k++) {
    
        // Calculate coins from bursting `k` last in this
        // range
        let coins
            = arr[left - 1] * arr[k] * arr[right + 1];

        // Recursively compute coins from the left and right
        // subarrays
        let leftCoins = getMaxCoins(left, k - 1, arr);
        let rightCoins = getMaxCoins(k + 1, right, arr);

        // Update maxCoins with the best option
        maxCoins = Math.max(maxCoins,
                            coins + leftCoins + rightCoins);
    }

    return maxCoins;
}

// Function to calculate the maximum coins
// obtainable by bursting all balloons
function maxCoins(arr) {

    // Add virtual balloons with value 1 at both ends of
    // `arr`
    let n = arr.length;
    arr.unshift(1);
    arr.push(1);

    // Call recursive helper on the full 
    // range of balloons
    return getMaxCoins(1, n, arr);
}

const arr = [ 3, 1, 5, 8 ];
console.log(maxCoins(arr));

Output
167

The above solution will have Exponential Time complexity.

Using Top-Down DP (Memoization) – O(n^3) Time and O(n^2) Space

If we notice carefully, we can observe that the above recursive solution holds the following two properties of Dynamic Programming:

  1. Optimal Substructure: The maximum coins obtained from bursting balloons in a range [left, right] depends on the optimal solution of subproblems [left, k-1] and [k+1, right], where k is the last balloon burst in the current range. By selecting each balloon k as the last to burst in the current range, we can combine the results of these subproblems to determine the maximum coins achievable for the range [left ,right].
  2. Overlapping Subproblems: In a purely recursive approach, the same subproblems are calculated multiple times. For example, when calculating the maximum coins for a range [1,n], the recursive calls may repeatedly calculate the maximum coins for the same subranges, such as [1, k-1]or [k+1, n]. This repetition leads to overlapping subproblems.

To avoid recomputing results for the same subproblems, we use a 2D DP array dp of size (n+2) × (n+2) (as virtual balloons with value 1 are also added at both ends of the arr[] to simplify the handling of boundary conditions) where dp[left][right] stores the maximum coins obtainable from bursting all balloons in the range [left, right]. We initialize all entries in dp to -1 and populate them using memoization as we calculate optimal subproblems.

C++
// C++ code of getting maximum value by
// bursting Balloons using memoization.

#include <bits/stdc++.h>
using namespace std;

// Recursive function to calculate maximum 
// coins from bursting balloons in range [left, right]
// with memoization (Top-Down DP)
int getMaxCoins(int left, int right, vector<int> &arr, 
                vector<vector<int>> &memo) {
  
    // If no balloons in this range, return 0
    if (left > right) return 0;

    // If the result is already computed, return it
    if (memo[left][right] != -1) return memo[left][right];

    int maxCoins = 0;

    // Try each balloon `k` in range [left, right] 
    // as the last balloon to burst
    for (int k = left; k <= right; k++) {
      
        // Calculate coins from bursting `k` 
        // last in this range
        int coins = arr[left - 1] * arr[k] * arr[right + 1];

        // Recursively compute coins from the left and 
        // right subarrays
        int leftCoins = getMaxCoins(left, k - 1, arr, memo);
        int rightCoins = getMaxCoins(k + 1, right, arr, memo);

        // Update maxCoins with the best option
        maxCoins = max(maxCoins, coins + leftCoins + rightCoins);
    }

    // Store the result in the memoization table
    memo[left][right] = maxCoins;

    return maxCoins;
}

// Function to calculate the maximum coins
// obtainable by bursting all balloons
int maxCoins(vector<int> &arr) {
  
      int n = arr.size();
  
    // Add virtual balloons with value 1 at 
      // both ends of `arr`
    arr.insert(arr.begin(), 1);
    arr.push_back(1);

    // Create a memoization table initialized to -1
    vector<vector<int>> memo(n + 2, vector<int>(n + 2, -1));

    // Call the recursive helper on the full 
      // range of balloons
    return getMaxCoins(1, n, arr, memo);
}

int main() {
  
    vector<int> arr = {3, 1, 5, 8};
    cout << maxCoins(arr);
    return 0;
}
Java
// Java code of getting maximum value by
// bursting Balloons using memoization.

class GfG {

    // Recursive function to calculate maximum
    // coins from bursting balloons in range [left, right]
    // with memoization (Top-Down DP)
    static int getMaxCoins(int left, int right, int[] arr,
                           int[][] memo) {

        // If no balloons in this range, return 0
        if (left > right)
            return 0;

        // If the result is already 
          // computed, return it
        if (memo[left][right] != -1)
            return memo[left][right];

        int maxCoins = 0;

        // Try each balloon `k` in range [left, right]
        // as the last balloon to burst
        for (int k = left; k <= right; k++) {

            // Calculate coins from bursting `k`
            // last in this range
            int coins
                = arr[left - 1] * arr[k] * arr[right + 1];

            // Recursively compute coins from the left and
            // right subarrays
            int leftCoins
                = getMaxCoins(left, k - 1, arr, memo);
            int rightCoins
                = getMaxCoins(k + 1, right, arr, memo);

            // Update maxCoins with the best option
            maxCoins = Math.max(maxCoins, coins + leftCoins
                                              + rightCoins);
        }

        // Store the result in the memoization table
        memo[left][right] = maxCoins;

        return maxCoins;
    }

    // Function to calculate the maximum coins
    // obtainable by bursting all balloons
    static int maxCoins(int[] arr) {

        // Add virtual balloons with value 1 at both ends of
        // `arr`
          
          int n = arr.length;
        int[] newArr = new int[n + 2];
        newArr[0] = 1;
        for (int i = 0; i < n; i++) {
            newArr[i + 1] = arr[i];
        }
        newArr[n + 1] = 1;

        // Create a memoization table 
          // initialized to -1
        int[][] memo = new int[n + 2][n + 2];
        for (int i = 0; i < n + 2; i++) {
            for (int j = 0; j < n + 2; j++) {
                memo[i][j] = -1;
            }
        }

        // Call the recursive helper on the full range of
        // balloons
        return getMaxCoins(1, n, newArr, memo);
    }

    public static void main(String[] args) {

        int[] arr = { 3, 1, 5, 8 };
        System.out.println(maxCoins(arr));
    }
}
Python
# Python code to get the maximum value by bursting Balloons.
# using memoization.

# Recursive function to calculate maximum
# coins from bursting balloons in range [left, right]
# with memoization (Top-Down DP)

def getMaxCoins(left, right, arr, memo):
  
    # If no balloons in this range, return 0
    if left > right:
        return 0

    # If the result is already computed, 
    # return it
    if memo[left][right] != -1:
        return memo[left][right]

    maxCoins = 0

    # Try each balloon `k` in range [left, right]
    # as the last balloon to burst
    for k in range(left, right + 1):
      
        # Calculate coins from bursting `k`
        # last in this range
        coins = arr[left - 1] * arr[k] * arr[right + 1]

        # Recursively compute coins from the left and
        # right subarrays
        leftCoins = getMaxCoins(left, k - 1, arr, memo)
        rightCoins = getMaxCoins(k + 1, right, arr, memo)

        # Update maxCoins with the best option
        maxCoins = max(maxCoins, coins + leftCoins + rightCoins)

    # Store the result in the memoization table
    memo[left][right] = maxCoins

    return maxCoins

# Function to calculate the maximum coins
# obtainable by bursting all balloons

def maxCoins(arr):
      
    n = len(arr);
    
    # Add virtual balloons with value 1 at
    # both ends of `arr`
    arr = [1] + arr + [1]

    # Create a memoization table initialized to -1
    memo = [[-1 for _ in range(n + 2)] for _ in range(n + 2)]

    # Call the recursive helper on the full 
    # range of balloons
    return getMaxCoins(1, n, arr, memo)


if __name__ == "__main__":
    arr = [3, 1, 5, 8]
    print(maxCoins(arr))
C#
// C# code to get the maximum value by 
// bursting Balloons using memoization.

using System;

class GfG {

    // Recursive function to calculate maximum
    // coins from bursting balloons in range [left, right]
    // with memoization (Top-Down DP)
    static int GetMaxCoins(int left, int right, int[] arr,
                           int[, ] memo) {

        // If no balloons in this range, return 0
        if (left > right)
            return 0;

        // If the result is already computed, return it
        if (memo[left, right] != -1)
            return memo[left, right];

        int maxCoins = 0;

        // Try each balloon `k` in range [left, right]
        // as the last balloon to burst
        for (int k = left; k <= right; k++) {

            // Calculate coins from bursting `k`
            // last in this range
            int coins
                = arr[left - 1] * arr[k] * arr[right + 1];

            // Recursively compute coins from the left and
            // right subarrays
            int leftCoins
                = GetMaxCoins(left, k - 1, arr, memo);
            int rightCoins
                = GetMaxCoins(k + 1, right, arr, memo);

            // Update maxCoins with the best option
            maxCoins = Math.Max(maxCoins, coins + leftCoins
                                              + rightCoins);
        }

        // Store the result in the memoization table
        memo[left, right] = maxCoins;

        return maxCoins;
    }

    // Function to calculate the maximum coins
    // obtainable by bursting all balloons
    static int MaxCoins(int[] arr) {

        // Add virtual balloons with value 1 at both ends of
        // `arr`
          int n = arr.Length;
        int[] newArr = new int[n + 2];
        newArr[0] = 1;
        for (int i = 0; i < n; i++) {
            newArr[i + 1] = arr[i];
        }
        newArr[n + 1] = 1;

        // Create a memoization table initialized to -1
        int[, ] memo = new int[n + 2, n + 2];
        for (int i = 0; i < n + 2; i++) {
            for (int j = 0; j < n + 2; j++) {
                memo[i, j] = -1;
            }
        }

        // Call the recursive helper on the full range of
        // balloons
        return GetMaxCoins(1, n, newArr, memo);
    }
    static void Main() {
        int[] arr = { 3, 1, 5, 8 };
        Console.WriteLine(MaxCoins(arr));
    }
}
JavaScript
// JavaScript code to get the maximum value by bursting
// Balloons using memoization.

function getMaxCoins(left, right, arr, memo) {

    // If no balloons in this range, return 0
    if (left > right)
        return 0;

    // If the result is already computed, return it
    if (memo[left][right] !== -1)
        return memo[left][right];

    let maxCoins = 0;

    // Try each balloon `k` in range [left, right]
    // as the last balloon to burst
    for (let k = left; k <= right; k++) {
    
        // Calculate coins from bursting `k`
        // last in this range
        let coins = arr[left - 1] * arr[k] * arr[right + 1];

        // Recursively compute coins from the left and
        // right subarrays
        let leftCoins = getMaxCoins(left, k - 1, arr, memo);
        let rightCoins
            = getMaxCoins(k + 1, right, arr, memo);

        // Update maxCoins with the best option
        maxCoins = Math.max(maxCoins,
                            coins + leftCoins + rightCoins);
    }

    // Store the result in the memoization table
    memo[left][right] = maxCoins;

    return maxCoins;
}

// Function to calculate the maximum coins
// obtainable by bursting all balloons
function maxCoins(arr) {

    // Add virtual balloons with value 1 at both ends of
    // `arr`
    let n = arr.length
    arr = [ 1, ...arr, 1 ];

    // Create a memoization table initialized to -1
    let memo = Array.from({length : n + 2},
                          () => Array(n + 2).fill(-1));

    // Call the recursive helper on the full range of
    // balloons
    return getMaxCoins(1, n, arr, memo);
}

let arr = [ 3, 1, 5, 8 ];
console.log(maxCoins(arr));

Output
167

Using Bottom-Up DP (Tabulation) – O(n^3) Time and O(n^2) Space

The approach is similar to the previous one, just instead of breaking down the problem recursively, we iteratively build up the solution by calculating in bottom-up manner. Maintain a dp[][] table such that dp[i][j] stores the maximum coins that can be obtained by bursting all the balloons between index i and j, inclusive.

C++
// C++ code of getting maximum value by
// bursting Balloons using tabulation.

#include <bits/stdc++.h>
using namespace std;

// Function to calculate maximum coins
// from bursting balloons in range [left, right]
int maxCoins(vector<int> &arr) {
  
      int n = arr.size();

    // Add virtual balloons with value 1 at both
      // ends of `nums`
    arr.insert(arr.begin(), 1);
    arr.push_back(1);

    // Initialize the dp table with 0
    vector<vector<int>> dp(n + 2, vector<int>(n + 2, 0));

    // Iterate over subarrays of increasing length
    for (int length = 1; length <= n; length++) {
        for (int left = 1; left <= n - length + 1; left++) {
            int right = left + length - 1;

            // Try every possible last balloon to burst
            for (int k = left; k <= right; k++) {
              
                // Calculate coins from bursting `k` 
                  // last in this range
                int coins = arr[left - 1] * arr[k] * arr[right + 1];

                // Add coins from the left and right 
                  // subarrays
                int totalCoins = coins + dp[left][k - 1] + dp[k + 1][right];

                // Update dp[left][right] with the maximum coins
                dp[left][right] = max(dp[left][right], totalCoins);
            }
        }
    }

    // Return the result from the dp table for
    // the full range of balloons
    return dp[1][n];
}

int main() {
  
    vector<int> arr = {3, 1, 5, 8};
    cout << maxCoins(arr);
    return 0;
}
Java
// Java code of getting maximum value by
// bursting Balloons using tabulation.

class GfG {

    // Function to calculate maximum coins
    // from bursting balloons in range [left, right]
    static int maxCoins(int[] arr) {
      
          int n = arr.length;

        // Add virtual balloons with value 1
        // at both ends of `nums`
        int[] nums = new int[n + 2];
        nums[0] = 1;
        nums[n + 1] = 1;
        for (int i = 0; i < n; i++) {
            nums[i + 1] = arr[i];
        }

        // Initialize the dp table with 0
        int[][] dp = new int[n + 2][n + 2];

        // Iterate over subarrays of increasing length
        for (int length = 1; length <= n; length++) {
            for (int left = 1; left <= n - length + 1;
                 left++) {
                int right = left + length - 1;

                // Try every possible last balloon to burst
                for (int k = left; k <= right; k++) {
                  
                    // Calculate coins from bursting `k`
                    // last in this range
                    int coins = nums[left - 1]
                                * nums[k]
                                * nums[right + 1];

                    // Add coins from the left and right
                    // subarrays
                    int totalCoins = coins + dp[left][k - 1]
                                     + dp[k + 1][right];

                    // Update dp[left][right] with the
                    // maximum coins
                    dp[left][right] = Math.max(
                        dp[left][right], totalCoins);
                }
            }
        }

        // Return the result from the dp table for the full
        // range of balloons
        return dp[1][n];
    }

    public static void main(String[] args) {
      
        int[] arr = { 3, 1, 5, 8 };
        System.out.println(maxCoins(arr));
    }
}
Python
# Python code of getting maximum value by
# bursting Balloons using tabulation.

# Function to calculate maximum coins 
# from bursting balloons in range [left, right]
def maxCoins(arr):
  
    n = len(arr)

    # Add virtual balloons with value 1
    # at both ends of `arr`
    arr = [1] + arr + [1]

    # Initialize the dp table with 0
    dp = [[0] * (n + 2) for _ in range(n + 2)]

    # Iterate over subarrays of increasing length
    for length in range(1, n + 1):
        for left in range(1, n - length + 2):
            right = left + length - 1

            # Try every possible last balloon
            # to burst
            for k in range(left, right + 1):
              
                # Calculate coins from bursting `k`
                # last in this range
                coins = arr[left - 1] * arr[k] * arr[right + 1]

                # Add coins from the left and right 
                # subarrays
                totalCoins = coins + dp[left][k - 1] + dp[k + 1][right]

                # Update dp[left][right] with the maximum coins
                dp[left][right] = max(dp[left][right], totalCoins)

    # Return the result from the dp table for the 
    # full range of balloons
    return dp[1][n]

arr = [3, 1, 5, 8]
print(maxCoins(arr))
C#
// C# code of getting maximum value by
// bursting Balloons using tabulation.

using System;

class GfG {
  
    // Function to calculate maximum coins
    // from bursting balloons in range [left, right]
    static int MaxCoins(int[] arr) {
      
        // Add virtual balloons with value
          // 1 at both ends of `nums`
          int n = arr.Length;
        int[] nums = new int[n + 2];
        nums[0] = 1;
        nums[n + 1] = 1;
        for (int i = 0; i < n; i++) {
            nums[i + 1] = arr[i];
        }

        // Initialize the dp table with 0
        int[, ] dp = new int[n + 2, n + 2];

        // Iterate over subarrays of increasing length
        for (int length = 1; length <= n; length++) {
            for (int left = 1; left <= n - length + 1;
                 left++) {
                int right = left + length - 1;

                // Try every possible last balloon to burst
                for (int k = left; k <= right; k++) {
                  
                    // Calculate coins from bursting `k`
                    // last in this range
                    int coins = nums[left - 1]
                                * nums[k]
                                * nums[right + 1];

                    // Add coins from the left and right
                    // subarrays
                    int totalCoins = coins + dp[left, k - 1]
                                     + dp[k + 1, right];

                    // Update dp[left][right] with the
                    // maximum coins
                    dp[left, right] = Math.Max(
                        dp[left, right], totalCoins);
                }
            }
        }

        // Return the result from the dp table for the full
        // range of balloons
        return dp[1, n];
    }

    static void Main() {
      
        int[] arr = { 3, 1, 5, 8 };
        Console.WriteLine(MaxCoins(arr));
    }
}
JavaScript
// JavaScript code of getting maximum value by
// bursting Balloons using tabulation.

function maxCoins(arr) {

    let n = arr.length;

    // Add virtual balloons with value 1 at both
    // ends of `arr`
    arr = [1, ...arr, 1];

    // Initialize the dp table with 0
    let dp = Array.from({length: n + 2}, () => Array(n + 2).fill(0));

    // Iterate over subarrays of increasing length
    for (let length = 1; length <= n; length++) {
        for (let left = 1; left <= n - length + 1; left++) {
            let right = left + length - 1;

            // Try every possible last balloon to burst
            for (let k = left; k <= right; k++) {
            
                // Calculate coins from bursting `k` last in
                // this range
                let coins = arr[left - 1] * arr[k] * arr[right + 1];

                // Add coins from the left and right
                // subarrays
                let totalCoins = coins + dp[left][k - 1]
                                 + dp[k + 1][right];

                // Update dp[left][right] with the maximum
                // coins
                dp[left][right] = Math.max(dp[left][right], totalCoins);
            }
        }
    }

    // Return the result from the dp table for the full
    // range of balloons
    return dp[1][n];
}

const arr = [3, 1, 5, 8];
console.log(maxCoins(arr));

Output
167

Unlock your potential with our DSA Self-Paced course, designed to help you master Data Structures and Algorithms at your own pace. In 90 days, you’ll learn the core concepts of DSA, tackle real-world problems, and boost your problem-solving skills, all at a speed that fits your schedule. With comprehensive lessons and practical exercises, this course will set you up for success in technical interviews and beyond.

And here's the challenge – join the Three 90 Challenge! Complete 90% of the course in 90 days, and you’ll earn a 90% refund. It's a great way to stay motivated, track your progress, and reward yourself for your dedication. Start the challenge today, and push your limits to achieve mastery in DSA!


Next Article

Similar Reads

three90RightbarBannerImg