Skip to content

Commit cb211ee

Browse files
Create Burst Balloons.java
1 parent 353d134 commit cb211ee

1 file changed

Lines changed: 56 additions & 0 deletions

File tree

LeetCode/Burst Balloons.java

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
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+
10+
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.
11+
12+
Return the maximum coins you can collect by bursting the balloons wisely.
13+
14+
15+
*/
16+
17+
18+
***** Solution *****
19+
20+
21+
22+
public int maxCoins_memo(int[] nums , int si , int ei , int[][] dp){ //si = starting index , ei = ending index
23+
if(dp[si][ei] != 0)
24+
return dp[si][ei];
25+
26+
int lele = si == 0 ? 1 : nums[si - 1]; //lele = leftelement
27+
int rele = ei == nums.length - 1 ? 1 : nums[ei + 1]; //rele = rightelement
28+
29+
int maxCoin = 0;
30+
for(int cut = si; cut <= ei; cut++){
31+
int lcost = cut == si ? 0 : maxCoins_memo(nums , si , cut - 1 , dp); //lcost:leftcost
32+
int rcost = cut == ei ? 0 : maxCoins_memo(nums , cut + 1 , ei , dp); //rcost:rightcost
33+
34+
maxCoin = Math.max(maxCoin , lcost + lele * nums[cut] * rele + rcost);
35+
}
36+
37+
return dp[si][ei] = maxCoin;
38+
}
39+
public int maxCoins(int[] nums) {
40+
int n = nums.length;
41+
int[][] dp = new int[n][n];
42+
43+
return maxCoins_memo(nums , 0 , n - 1 , dp);
44+
}
45+
46+
47+
48+
49+
50+
/*
51+
Sample input: [3,1,5,8]
52+
53+
Sample Output: 167
54+
55+
56+
*/

0 commit comments

Comments
 (0)