|
| 1 | +/ // Leetcode Ques No. : 312 |
| 2 | + // Problem Link: https://leetcode.com/problems/burst-balloons/ |
| 3 | + |
| 4 | + |
| 5 | + ***** problem statement ***** |
| 6 | + |
| 7 | + /* |
| 8 | + You are given n balloons, indexed from 0 to n - 1. Each balloon is painted with a number on it represented by an array nums. You are asked to burst all the balloons. |
| 9 | + If you burst the ith balloon, you will get nums[i - 1] * nums[i] * nums[i + 1] coins. If i - 1 or i + 1 goes out of bounds of the array, then treat it as if there is a balloon with a 1 painted on it. |
| 10 | + Return the maximum coins you can collect by bursting the balloons wisely. |
| 11 | + */ |
| 12 | + |
| 13 | + |
| 14 | + ***** Solution ***** |
| 15 | + |
| 16 | + |
| 17 | + |
| 18 | + public int maxCoins_memo(int[] nums , int si , int ei , int[][] dp){ //si = starting index , ei = ending index |
| 19 | + if(dp[si][ei] != 0) |
| 20 | + return dp[si][ei]; |
| 21 | + |
| 22 | + int lele = si == 0 ? 1 : nums[si - 1]; //lele = leftelement |
| 23 | + int rele = ei == nums.length - 1 ? 1 : nums[ei + 1]; //rele = rightelement |
| 24 | + |
| 25 | + int maxCoin = 0; |
| 26 | + for(int cut = si; cut <= ei; cut++){ |
| 27 | + int lcost = cut == si ? 0 : maxCoins_memo(nums , si , cut - 1 , dp); //lcost:leftcost |
| 28 | + int rcost = cut == ei ? 0 : maxCoins_memo(nums , cut + 1 , ei , dp); //rcost:rightcost |
| 29 | + |
| 30 | + maxCoin = Math.max(maxCoin , lcost + lele * nums[cut] * rele + rcost); // maxcoin means the maximum number of coins collect after balloon burst |
| 31 | + } |
| 32 | + |
| 33 | + return dp[si][ei] = maxCoin; |
| 34 | + } |
| 35 | + public int maxCoins(int[] nums) { |
| 36 | + int n = nums.length; |
| 37 | + int[][] dp = new int[n][n]; |
| 38 | + |
| 39 | + return maxCoins_memo(nums , 0 , n - 1 , dp); |
| 40 | + } |
| 41 | + |
| 42 | + |
| 43 | + |
| 44 | + |
| 45 | + |
| 46 | + /* |
| 47 | + Sample input: [3,1,5,8] |
| 48 | + |
| 49 | + Sample Output: 167 |
| 50 | + |
| 51 | + |
| 52 | + */ |
0 commit comments