Easy Java solution


  • 0
    public class Solution {
        public int maxCoins(int[] nums) {
            int n = nums.length;
            int[][] coins = new int[n][n];
            for (int len = 1; len <= n; len++) {
                for (int i = 0; i+len <= n; i++) {
                    int j = i+len-1;
                    int beyondLeft = i - 1 >= 0 ? nums[i-1] : 1; // left side beyond the sub interval
                    int beyondRight = j + 1 < n ? nums[j+1] : 1; // right side beyond the sub interval
                    for (int k = i; k <= j; k++) {
                        int left = k-1 >= i ? coins[i][k-1] : 0; // left i,k-1 
                        int right = k+1 <= j ? coins[k+1][j] : 0; // right k+1,j
                        // treat every balloon k between i and j as the the last burst balloon
                        // calculate the maximum coins between i, j.
                        coins[i][j] = Math.max(beyondLeft * nums[k] * beyondRight + left + right, coins[i][j]);
                    }
                }
            }
            return n == 0 ? 0 : coins[0][n-1];
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.