Givennballoons, indexed from0ton-1. Each balloon is painted with a number on it represented by arraynums. You are asked to burst all the balloons. If the you burst ballooniyou will getnums[left] * nums[i] * nums[right]coins. Here left and right are adjacent indices of i. After the burst, the left and right then becomes adjacent.
Find themaximumcoins you can collect by bursting the balloons wisely.
publicclassSolution {publicintmaxCoins(int[] nums) {if (nums ==null||nums.length==0){return0; } nums =init(nums);int[][] dp =newint[nums.length][nums.length];for (int i =nums.length-1; i >=0; i--) {for (int j = i +2; j <nums.length; j++) {for (int k = i +1; k < j; k++) { dp[i][j] =Math.max(dp[i][j], dp[i][k] + dp[k][j] + nums[i] * nums[k] * nums[j]); //状态转移利用小区间最优解更新大区间 } } }return dp[0][nums.length-1]; }publicint[] init(int[] nums){ //初始化数组,头部和尾部插入1int[] temp =newint[nums.length+2]; temp[0] =1;for(int i =1; i <temp.length-1; i++){ temp[i] = nums[i -1]; } temp[temp.length-1] =1;return temp; }}
classSolution:""" @param nums: A list of integer @return: An integer, maximum coins """defmaxCoins(self,nums):ifnot nums:return0# [4,1,5] => [1,4,1,5,1] nums = [1,*nums,1]return self.memo_search(nums, 0, len(nums) -1, {})defmemo_search(self,nums,i,j,memo):if i == j:return0if (i, j) in memo:return memo[(i, j)] best =0for k inrange(i +1, j): left = self.memo_search(nums, i, k, memo) right = self.memo_search(nums, k, j, memo) best =max(best, left + right + nums[i] * nums[k] * nums[j]) memo[(i, j)]= bestreturn best