Burst Baloons - Dynamic Programming - Leetcode 312 - Python

  Рет қаралды 76,219

NeetCode

NeetCode

Күн бұрын

Пікірлер: 126
@NeetCode
@NeetCode 3 жыл бұрын
💡 DP Playlist: kzbin.info/www/bejne/bWTVZH6Nnqqpr80
@ClaudioCarvalhoo
@ClaudioCarvalhoo 3 жыл бұрын
Just wanted to say that your videos are the best Leetcode question explanations on KZbin by a long shot in my opinion. Thanks and keep going!
@NeetCode
@NeetCode 3 жыл бұрын
Thanks Umbreon, you were always my favorite Eeveelution!
@CarlJohnson-iv7sn
@CarlJohnson-iv7sn 2 жыл бұрын
@@NeetCode lol
@sarthuaksharma
@sarthuaksharma 3 жыл бұрын
I was stuck on this problem for hours. Going through the discuss forum but was not able to get the feel on how to approach and I thought let's see if Neetcode has this. Thank you so much man. One suggestion though if you encounter similar problems It will be really helpful if you can put those in the description. Keep up the good work man
@poptart007-b2r
@poptart007-b2r 2 жыл бұрын
The backtracking solution with some kinda cache is easy to code if you know how to code permutations, but omfg i could never have guessed the tricks on this one by myself, and even less in an interview setting, thanks a lot for the explanation! Here is an iterative bottom up solution that worked for me at 66% faster: class Solution: def maxCoins(self, nums: List[int]) -> int: nums = [1]+nums+[1] dp = [[0 for r in range(len(nums))] for l in range(len(nums))] for l in range(len(nums)-2,0,-1): for r in range(1,len(nums)-1): if l
@tabeebyeamin9986
@tabeebyeamin9986 3 жыл бұрын
Yes, this code passes 69/70 cases and TLEs on the last one. But it seems you can't do better than O(n^3) anyway, so I am going to use this solution if I get it an interview. I spent 45 minutes attempting this myself and the best I could do was the glorious 2^n bruteforce solution lol. I love that you keep it real and mention you have no idea how we would be able to solve it without seeing it
@vinayak186f3
@vinayak186f3 3 жыл бұрын
Can I have that 2^n solution please .
@saiachyuth3460
@saiachyuth3460 3 жыл бұрын
@@vinayak186f3 It's the same solution without dp
@MrPanthershah
@MrPanthershah 2 жыл бұрын
Bruteforce isn't 2^n, it's n^n, I think that's what you meant.
@nlke182
@nlke182 2 жыл бұрын
If you use @cache decorator it can pass.
@CaradhrasAiguo49
@CaradhrasAiguo49 2 жыл бұрын
@@MrPanthershah Brute force would be to generate all permutations, which is N!, which is asymptomatically less than N^N per Stirling's formula
@jyotioh3723
@jyotioh3723 2 жыл бұрын
I hope no one gets discouraged while trying to get through this one. I'm almost there, lmao.
@Hiroki-Takahashi
@Hiroki-Takahashi 9 ай бұрын
I was being so discourged while watching this video lol (I mean, NeetCode's explanation was excellent. This problem is just god damn hard)
@MAhmadian
@MAhmadian 3 жыл бұрын
Thank you for clever solution awesome explanation. It throws an TLE which can be fixed by handling the special case which all elements in the list are the same number. if len(nums) > 1 and len(set(nums)) == 1: return (nums[0] ** 3) * (len(nums) - 2) + nums[0] ** 2 + nums[0]
@sergeychepurnov1328
@sergeychepurnov1328 3 жыл бұрын
I think it ugly, but works for Leetcode's last test case that I believe doesn't needed at interview: //one special test case handled manually //check roughly if (nums.length > 10 && nums[0] == nums[1] && nums[1] == nums[2]) { Set set = new HashSet(); for (int num : nums) { set.add(num); } //check exactly if (set.size() == 1) { int num = nums[0]; // 1 100 100 100 ... 100 100 100 1 - calculate all middle values: (num*num*num)*(nums.length - 2) // 1 100 100 1 - calculate 2 last: num*num // 1 100 1 - calculate 1 last: num int max = (num*num*num)*(nums.length - 2) + num*num + num; return max; } }
@ayeshsalah
@ayeshsalah 3 жыл бұрын
Could please explain why this works ?
@dollyvishwakarma2
@dollyvishwakarma2 2 жыл бұрын
this did not work for me
@ahmedrebei8138
@ahmedrebei8138 3 жыл бұрын
3:58 I think the complexity would be n! (you get one less item on each level of the tree)
@vijayola7597
@vijayola7597 2 жыл бұрын
yes
@sadekjn
@sadekjn Жыл бұрын
yes, that solution basically generates all the permutations, which is n!
@wintersol9921
@wintersol9921 3 жыл бұрын
So glad to find this video. I have been trying to understand how to solve this problem for 2 days. You explained it in 10 minutes. Thank you very much.
@bmusuko
@bmusuko 2 жыл бұрын
if you guys got TLE on the last testcase, try to change dp hashmap into 2d matrix, since array lookup slightly faster than hashmap lookup. And also you can put `@cache` on top of dfs function
@girrajjangid4681
@girrajjangid4681 2 жыл бұрын
Thanks @bram. It worked by changing dict to 2D list
@forresthu6204
@forresthu6204 3 жыл бұрын
Thanks
@omartahboub2900
@omartahboub2900 3 жыл бұрын
Good Point ! If your interviewer was so busy that day and had bunch of deliverable to be completed, and forgot to give you any useful hints and poor candidate who prepped for so many sleepless weeks to eventually be marked with "No Hire" for such problem the candidate would not encounter working at that company. What a sad reality ! I would imagine many candidates would just memorize the solution and go with odds of "Hit or Miss" until the next 6 or 12-month cool-down cycle.
@VarunMittal-viralmutant
@VarunMittal-viralmutant 2 жыл бұрын
I have seen architect level ppl stuck on a problem for weeks, and then when they have 'light bulb' moment, they ask the same question in their next interview. Imagine the poor candidate has just 40 minute to crack the question 😢
@donotreportmebro
@donotreportmebro Жыл бұрын
@@VarunMittal-viralmutant that's a bar raiser
@VarunMittal-viralmutant
@VarunMittal-viralmutant Жыл бұрын
@@donotreportmebro No matter what you call it. It is unfair and unjust to the candidate. While you were stuck for it for weeks and had multiple ppl brainstorming the solution, the poor candidate is all alone, already under pressure and has just 30 minute to come up with the solution.
@secretdev1559
@secretdev1559 2 жыл бұрын
Awesome explanation! There are a few more cases that were added to LC which lead to a TLE despite the same num check. If one takes the DFS approach here and instead leverages iteration, the overhead of the stack can be avoided and a TLE can be avoided. Although the algorithm's RT is still O(n^3) with O(n^2) space complexity. I think that the time limit band on the problem needs to be increased.
@MrKB_SSJ2
@MrKB_SSJ2 Жыл бұрын
I watch every LeetCode video of yours!
@chuckchen2851
@chuckchen2851 3 жыл бұрын
Tried the lru_cache and the manual memoization way as done in the video, both TLE on the 69th case, which has 500 elements. Is the bottom-up approach somehow more efficient than the top-down?
@nathanx.675
@nathanx.675 3 жыл бұрын
Same...
@8Trails50
@8Trails50 3 жыл бұрын
it is more efficient - less overhead in computation which leads to it barely being accepted.
@jongxina3595
@jongxina3595 2 жыл бұрын
I did it bottom up and worked like a charm first try ✨️
@Simran_048
@Simran_048 4 ай бұрын
best simple explanation, i was not getting idea before watching this
@ashwinnema06
@ashwinnema06 2 жыл бұрын
Best explanation I ever found on youtube
@NeetCode
@NeetCode 2 жыл бұрын
Glad it was helpful!
@houmankamali5617
@houmankamali5617 2 жыл бұрын
If it helps, the way that I justified one could intuitively arrive at the trick is to think about how we could arrive at a subproblem in which the order of the elements is the original list is not modified. The initial approach of starting from popping an element and then calculating the result for the subproblems does not work because the order of the elements in the subproblems are different than the original problem, so we can instead think "how would it help me find a solution if I had the cache result for some consecutive number of the elements?"
@stevenmo1586
@stevenmo1586 2 жыл бұрын
great insight Houman!
@harimonting01
@harimonting01 9 ай бұрын
But before deciding to look for possible subproblem, how can we intuitively conclude that this is a dp problem?
@farleylai1102
@farleylai1102 2 жыл бұрын
Solution to TLE: 1. Iterative 2. Use matrix instead of hash map cache def maxCoins(self, nums: List[int]) -> int: from collections import Counter nums = [1] + nums + [1] dp = [[0] * len(nums) for _ in range(len(nums))] for L in range(len(nums) - 2, 0, -1): for R in range(L, len(nums) - 1): for i in range(L, R+1): coins = nums[L-1] * nums[i] * nums[R+1] coins += dp[L][i-1] + dp[i+1][R] dp[L][R] = max(dp[L][R], coins) return dp[1][len(nums) - 2]
@ShamsNahid-gc1cx
@ShamsNahid-gc1cx 7 ай бұрын
Specially, in JS, without 2d matrix cache, it got a TLE. Thanks
@snowboarder981
@snowboarder981 9 ай бұрын
I really appreciate the work you put into these videos. Your videos are easily the best explanations. I love that you draw things out and talk about multiple solutions before moving to the code. You are best my friend!
@albertjtyeh53
@albertjtyeh53 3 жыл бұрын
It's TLE-ing on the 69/70th case now
@chowtuk
@chowtuk Жыл бұрын
the most unsatisfying video from neetcode
@Rohan-hj9gg
@Rohan-hj9gg 3 жыл бұрын
Thanks for this, can we have video for palindrome partitioning (MCM variation)
@vinayakmikkal
@vinayakmikkal 2 жыл бұрын
What if the array is [3, 1, 5, 8, 2] and the order of popping is [1, 8, 3, 2, 5] so at the end the cost that needs to be calculated is 3*5*2 + other_part, I'm not able to see a situation where the multiplication of 3*5*2 taking place. Am I missing anything?
@helloadventureworld
@helloadventureworld 6 ай бұрын
thanks for the video on this one it wasn't an easy one to get to be honest and your explanation made it way easier on me ❤❤❤❤
@sheltonsong6120
@sheltonsong6120 2 жыл бұрын
Thanks for the solution!!! You are the best! I copy paste your solution to Leetcode, and the judge result is Time Limit Exceeded. I believe the solution is definitely correct though, have you tried to submit the results? Leetcode sucks!
@itachid
@itachid Жыл бұрын
I think there's a mistake at 5:58 when Neet tells that for an array of size N there can be at most N^2 subarrays. But aren't there actually (N * (N + 1)) / 2 subarrays for an array of size N?
@Ren-j7n
@Ren-j7n Жыл бұрын
Well, we don't really care about the specific constants and thereby it is O(N^2) subarrays.
@sapnavats9105
@sapnavats9105 3 жыл бұрын
What is the need to initialize dp[(l,r)] to 0 and then update it as max of 0 and the newly computed value?
@chessingh
@chessingh 3 жыл бұрын
because dp is a dictionary and it will give key error, if not already there in the dictionary, try it without initialization you will see
@DavidDLee
@DavidDLee Жыл бұрын
The reason for initializing to 0 in L12 and then taking the max at L16 is because the code iterates over all nums between [l, r] and finds the max at that range. Now, you must find the max in [l, r], otherwise you'd get the wrong answer (*NOT* a key error though), because you'd probably just take the last value in the range that is likely less than max. Initializing to 0 in L12 is just a convenience, so you could use max also on the first iteration. 0 is guaranteed to be less than any of the possible values.
@hwang1607
@hwang1607 9 ай бұрын
This is a crazy question
@SreyesSrinivasan
@SreyesSrinivasan 2 жыл бұрын
Fantastic explanation man! Keep up the great work
@zelfrax
@zelfrax 2 ай бұрын
@5:17 you made a mistake. We have n! possible combinations. Phrasing it in terms of subsequences does not make sense because we are not concerned with subsequences in this problem.
@moonhan2157
@moonhan2157 2 ай бұрын
You are not correct. Subsequences are important in the subproblem and its 2^n subsequences.
@VishalKumar-kr9me
@VishalKumar-kr9me Жыл бұрын
What made you to not check l == r instead go with l > r as the base condition? Could you please explain
@akhma102
@akhma102 3 ай бұрын
Thanks, Neet!
@CaptainDeadpool53
@CaptainDeadpool53 4 ай бұрын
Is there a way to solve this without using memoization, like the regular DP?
@ammarqureshi2155
@ammarqureshi2155 3 жыл бұрын
great explanation, keep it up mate :)
@sauravgupta7415
@sauravgupta7415 2 жыл бұрын
Your voice is sounds like "Hello everyone, this is your daily dose of internet"
@chenzhuo9
@chenzhuo9 3 жыл бұрын
I got TLE with the same code rip
@veeresh4441
@veeresh4441 3 жыл бұрын
fck, there is no way I could think this in an interview
@NeetCode
@NeetCode 3 жыл бұрын
me neither probably, im sure 90% of interviewers would give you a hint tho.
@BeheadedKamikaze
@BeheadedKamikaze 2 жыл бұрын
@@NeetCode Would you mind explaining how you did arrive at this solution? It's not exactly intuitive. Edit: in case it wasn't clear, I do understand why it works. Just wondering by what process you managed to think of doing this.
@张灏琼
@张灏琼 Жыл бұрын
why the range is r+1 in L13???
@ameynaik2743
@ameynaik2743 3 жыл бұрын
Is there a list of problems on leetcode which fall under this category?
@DarkOceanShark
@DarkOceanShark 2 жыл бұрын
Where you able to find?
@mohakparekh8671
@mohakparekh8671 Жыл бұрын
Excellent explanation! There is one part which I am not able to comprehend. Why can't we use the caching with subsequence? There are 2^n subsequences, but won't the caching of that subproblems help us?
@mohakparekh8671
@mohakparekh8671 Жыл бұрын
@@numbtubeyou Understood, thanks
@MuratJumashev
@MuratJumashev 2 жыл бұрын
A possible follow-up question: give me the list of balloons you popped to get these coins 😅 Haven't solved this follow-up myself yet. Whenever I get to the solution, I think I'll have a better understanding of this problem 💪
@milseq
@milseq 11 ай бұрын
This is one of those problems where I'm just going to hope I don't get it.
@samarthtandale9121
@samarthtandale9121 Жыл бұрын
I think the time complexity of brute force will be n! Right?
@akshay-kumar-007
@akshay-kumar-007 Жыл бұрын
This looks like a variation of MCM. Is my intuition correct?
@nathanx.675
@nathanx.675 3 жыл бұрын
This is brilliant!
@АфанасийШереметьев-б5ч
@АфанасийШереметьев-б5ч 6 ай бұрын
A moment of silence for those who got this question in an interview (bonus points for it being the first)
@keshavmn7283
@keshavmn7283 3 ай бұрын
I recently got this as the first question in the second round 😢
@dataman4503
@dataman4503 2 жыл бұрын
I would assume that the interviewer wanted to fail you if they ask you this question in interview.
@NeetCode
@NeetCode 2 жыл бұрын
lol me too
@sagarpotnis1215
@sagarpotnis1215 2 жыл бұрын
there should be a counter for the time neetcode said "pop" in this video 😂
@linli7049
@linli7049 3 жыл бұрын
Awesome solution!
@tomtran6936
@tomtran6936 2 жыл бұрын
Wow. Really awesome trick and thought process. Nice explanation. Appreciated!. If you don't mind to share how much time you took to figure out of this solution?
@kalpanagupta6166
@kalpanagupta6166 4 ай бұрын
I didn't get why did you compute max operation?
@GetToKnowShaggy
@GetToKnowShaggy 4 ай бұрын
I think its time to solve this question again with a iterative approach
@mahedihassanrabby9553
@mahedihassanrabby9553 Жыл бұрын
Best of the best❤
@jonaskhanwald566
@jonaskhanwald566 3 жыл бұрын
MAXIMUM PROFIT IN JOB SCHEDULING?
@chenzhuo9
@chenzhuo9 3 жыл бұрын
dito
@nardindev
@nardindev 8 ай бұрын
i did it in js like this function maxCoins(nums) { const n = nums.length; const dp = Array(n + 2).fill(0).map(() => Array(n + 2).fill(0)); const balloons = [1, ...nums, 1]; for (let len = 1; len
@kashishsharma6809
@kashishsharma6809 2 жыл бұрын
oh god! such a hard ques. still don't know how will this recursive func will cover all the cases.
@rhapsody9442
@rhapsody9442 2 жыл бұрын
For those who get a TLE, try to add a @lru_cache(None) before the dfs function. Though this may be opportunistic, but it does work for me :) Got this from a leetcode discuss but I cannot understand that solution. This neet solution is within my understanding.
@derekmiller9520
@derekmiller9520 Жыл бұрын
Wouldn't brute force be O(n!) complexity?
@venkatarakesh1698
@venkatarakesh1698 3 жыл бұрын
Good explanation
@Randomisticful
@Randomisticful 3 жыл бұрын
I wish there were Java solutions using "proper English". But still, this does the job. Thanks!
@joydeeprony89
@joydeeprony89 2 жыл бұрын
YOU ARE SUPER HUMAN, SAME AS MESSI IN FOOTBALL. THANKS FOR MAKING OUR LIFE EASIER SPECIALLY DEV LIKE ME WHO IS BELOW AVERAGE BUT HAVING AN AMBITION OF WORKING FOR TIER ONE PRODUCT COMPANY.
@arnabpersonal6729
@arnabpersonal6729 3 жыл бұрын
very good approach but giving TLE
@hanjiang9888
@hanjiang9888 2 жыл бұрын
it works with python 2 but not python 3 on leetcode. Does anyone meet the same problem?
@syeds6789
@syeds6789 3 жыл бұрын
Thanks 😊
@chowtuk
@chowtuk Жыл бұрын
It would be better to understand if this video is like others DP video which draw a grash to run the solution's algorithm , because this is quiet complex to understand, hard to implement how it actually run in my brain
@wintersol9921
@wintersol9921 3 жыл бұрын
Does anyone else get Time Limit Exceeded error when submitting it?
@dk20can86
@dk20can86 2 жыл бұрын
This one nearly killed me 😮‍💨
@gauravchauhan7412
@gauravchauhan7412 2 жыл бұрын
best video
@m.y.7230
@m.y.7230 7 ай бұрын
Matrix Chain Multiplication would be easier approach
@shouryansharma9441
@shouryansharma9441 2 жыл бұрын
This solution is getting TLE
@prathamhebbar5800
@prathamhebbar5800 3 ай бұрын
This question makes me ask myself what is the meaning of life?
@abhayphanse9509
@abhayphanse9509 Жыл бұрын
classic IT IS WHAT IT IZ problem
@흘러가는대로-t7j
@흘러가는대로-t7j 3 жыл бұрын
Sooo clean
@fdm6334
@fdm6334 2 жыл бұрын
This solution gives TLE now.
@rackstar2
@rackstar2 2 жыл бұрын
this just throws a type error
@Super111111111111Man
@Super111111111111Man Жыл бұрын
Still not understand, help!
@Rohan-hj9gg
@Rohan-hj9gg 3 жыл бұрын
The solution does not work for the last test case.
@sushantrocks
@sushantrocks 3 жыл бұрын
Smells like matrix chain mult
@darshanputtaswamy3199
@darshanputtaswamy3199 2 жыл бұрын
Yep, I smelt the same
@joshithmurthy6209
@joshithmurthy6209 2 жыл бұрын
Most crip explaination on youtube
@TankNSSpank
@TankNSSpank 3 жыл бұрын
genius
@Philgob
@Philgob 4 ай бұрын
Dafuq is this
@dataman4503
@dataman4503 2 жыл бұрын
Meticulous explanation...
@shrn
@shrn 11 ай бұрын
Why is the solution so simple?
@Mnogarithm
@Mnogarithm Жыл бұрын
@ChinmayAnaokar-xm4ci
@ChinmayAnaokar-xm4ci Жыл бұрын
C# Implementation of above code with all test cases passed public class Solution { public int MaxCoins(int[] nums) { List lst = nums.ToList(); lst.Insert(0, 1); lst.Insert(lst.Count, 1); int count = lst.Count; int[,] dp = new int[count, count]; return DFS(1,lst.Count-2,dp,lst); } private int DFS(int l,int r,int [,] dp,Listnums) { if (l > r) return 0; if (dp[l, r] != 0) return dp[l, r]; dp[l, r] = 0; for(int i=l;i< r+1;i++) { int coins = nums[l - 1] * nums[i] * nums[r + 1]; coins = coins + DFS(l, i - 1, dp, nums) + DFS(i+1, r, dp, nums); dp[l, r] = Math.Max(dp[l, r], coins); } return dp[l, r]; } }
@indrajitbagchi7313
@indrajitbagchi7313 Ай бұрын
its matrix chain multiplication in disguise
@shaamidrees6036
@shaamidrees6036 2 жыл бұрын
Thanks
Making an Algorithm Faster
30:08
NeetCodeIO
Рет қаралды 192 М.
Climbing Stairs - Dynamic Programming - Leetcode 70 - Python
18:08
Andro, ELMAN, TONI, MONA - Зари (Official Music Video)
2:50
RAAVA MUSIC
Рет қаралды 2 МЛН
Wednesday VS Enid: Who is The Best Mommy? #shorts
0:14
Troom Oki Toki
Рет қаралды 50 МЛН
N-Queens - Backtracking - Leetcode 51 - Python
17:51
NeetCode
Рет қаралды 187 М.
DP 51. Burst Balloons | Partition DP | Interactive G-Meet Session Update
34:00
How to Solve ANY LeetCode Problem (Step-by-Step)
12:37
Codebagel
Рет қаралды 337 М.
Balloon burst problem dynamic programming | Leetcode #312
27:25
Word Break - Dynamic Programming - Leetcode 139 - Python
15:35
LeetCode was HARD until I Learned these 15 Patterns
13:00
Ashish Pratap Singh
Рет қаралды 711 М.
Word Ladder - Breadth First Search - Leetcode 127 - Python
17:06
How I would learn Leetcode if I could start over
18:03
NeetCodeIO
Рет қаралды 765 М.
Andro, ELMAN, TONI, MONA - Зари (Official Music Video)
2:50
RAAVA MUSIC
Рет қаралды 2 МЛН