Тёмный

Stone Game II - Leetcode 1140 - Python 

NeetCodeIO
Подписаться 200 тыс.
Просмотров 23 тыс.
50% 1

Опубликовано:

 

26 сен 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 71   
@ary_21
@ary_21 Год назад
At 11:42 i realised Alice and Bob are playing with me and not with each other
@LasTCursE69
@LasTCursE69 Месяц назад
This is by far the most confusing problem I've encountered on leetcode..
@sarwesharivazhagan5085
@sarwesharivazhagan5085 Месяц назад
for those who getting confused about bob's turn here is a tip to think of it... firstly we're only care about alice's score and our funtion only returns the alice score till here everything is fine.. the confusing part is bob's trun.. to understand it just image you as bob and you can only able to calculate what alice's score(through our func) if you make any move.. so as an opponent you try to make a move that force alice to have a least score possible... so we return that least score alice could score in bob's turn.. it is bit confusing but may be give you an another perspective to think of..
@ankitkushwaha8577
@ankitkushwaha8577 Месяц назад
Thanks bro
@Antinormanisto
@Antinormanisto Месяц назад
I still don't understand what the hell is going on and what do I do
@TheLearningLab898
@TheLearningLab898 Месяц назад
you not alone bro🫂
@satyadheeraj6081
@satyadheeraj6081 Месяц назад
@@TheLearningLab898 same here man 🥹
@thunder_cs
@thunder_cs Месяц назад
same
@erickjhormanromero6905
@erickjhormanromero6905 Месяц назад
Same
@reckyru
@reckyru Год назад
DP is pain and makes me cry
@ParodyCSEDept
@ParodyCSEDept Месяц назад
I am really happy to find that this video has word by word the same logic which I used to solve this one
@apputadhiyal9451
@apputadhiyal9451 Месяц назад
Almost solved it myself but forgot that res should be initialised with int_max in case of bob, made this change and code was accepted. Thank you for the video
@MP-ny3ep
@MP-ny3ep Год назад
Phenomenal explanation. Thank you!
@voidpointer398
@voidpointer398 Месяц назад
To anyone who is confused by this problem Forget about code and solution Try to make recursive decision tree on small length array and you will be able to prove why is dp working here DP only works on overlapping sub problems, it is very easy to prove it for this problem if you try it using pen and paper Once you are able to solve it using pen and paper then write the code, I believe you will be able to write your own solution. And if you are not able to solve it then watching tutorial will help you click in what exactly you weren't thinking correctly.
@namandubey8348
@namandubey8348 Месяц назад
i wonder how long will it me to solve these kind of problem by myself
@RomanFalcon13
@RomanFalcon13 Год назад
Thank you king, keep it up!
@Calypso1406
@Calypso1406 Год назад
idk how to come up with these kinds of solutions and im genuinely lost
@siddhantvishnu4309
@siddhantvishnu4309 Месяц назад
Exactly what I had in mind. Just had a few isues coding it up. Great video
@lesterdelacruz5088
@lesterdelacruz5088 9 дней назад
I'm still a bit confused of the intuition behind minimizing bob's score. I thought we simple call backtrack without for his case without worrying about it's return. But doing it that way is not equivalent to minimizing his score. I need to mull over that for a few days to really understand it.
@sahilthukral4948
@sahilthukral4948 Месяц назад
I was also confused by bob's turn Initially I thought the problem will become recursive with the same logic for both Alice and Bob (where both of them will try to maximise there score) so the solution will be max of ( total_sum - (recursively max possible for Bob in sub problem) ) , but later I realised that the goal of the game is for Alice to get max , where bob is not trying to max its own score but to minimise the score of Alice as much as it can , hope that helps
@朴云峰
@朴云峰 Год назад
take inspirations from your stone gameIII solution, I tried to calculate the max diff of Alice -Bob, then return the sum of piles - diff divided by 2, it works!
@gangstacoder4234
@gangstacoder4234 Год назад
hey i tried that too...can you elaborate or paste the code (if possible)
@朴云峰
@朴云峰 Год назад
@@gangstacoder4234 var stoneGameII = function (piles) { let cache = new Map() let sum = piles.reduce((acu, cur) => acu + cur, 0) function dfs(i, M) { if (i >= piles.length) { return 0 } if (cache.has(`${i}|${M}`)) { return cache.get(`${i}|${M}`) } let res = -Infinity let total = 0 for (let j = i; j < 2 * M + i; j++) { if (j >= piles.length) { break } total += piles[j] res = Math.max(res, total - dfs(j + 1, Math.max(M, j - i + 1))) } cache.set(`${i}|${M}`, res) return res } let diff = dfs(0, 1) return (sum + diff) / 2 };
@tofahub
@tofahub Год назад
This one is more helpful@@朴云峰
@theman-d
@theman-d Месяц назад
I havethis error "" TypeError: inf is not valid value for the expected return type integer ""
@sheruloves9190
@sheruloves9190 Месяц назад
Simply amazing!!
@6kostia
@6kostia Год назад
Nice solution, but it's better to ignore Bob's existence, Alice plays against herself as Bob and Alice are actually the same player.
@ivanzaplatar9033
@ivanzaplatar9033 Год назад
This is what I was thinking. What would the recurrence relation be?
@6kostia
@6kostia Год назад
@@ivanzaplatar9033 res = max(res, (sum(piles[i:])- dfs(i + x, max(x, m)))) It actually runs faster, around 200 ms
@NeetCodeIO
@NeetCodeIO Год назад
Does the sum(piles[I:]) run in O(n) time? I believe that may affect the overall time complexity
@ADITYA-fk1zy
@ADITYA-fk1zy Год назад
​@@NeetCodeIO we pre-compute the suffixsum in a array and use that array so it's O(1) to get sum.
@luizfelipe2330
@luizfelipe2330 Месяц назад
For sure this one is one of the best videos that you did.
@jaatharsh
@jaatharsh Месяц назад
true saviour, thanks once again
@mutianzhu5128
@mutianzhu5128 Месяц назад
Reminds me of minimax algorithm.
@business_central
@business_central Год назад
Could anyone please clarify to me why use "not Alice" in both Alice & Bob's turn ? (in the res calculations) ? I really just didn't get that specific point. Otherwise all clear as usual! Thank you Neetcode!
@ADITYA-fk1zy
@ADITYA-fk1zy Год назад
consider initilally alice = True (it means its alice turn now),when we say " not alice " it will become bob's turn right because not alice will be false now,simillarly if its bobs turn now it means alice variable must be false ,so next turn would be alice so "not alice " will become true in that case. In simple terms if its alice's turn "alice == true",else if its bob's turn "alice == false" hope you understand.
@business_central
@business_central Год назад
@@ADITYA-fk1zy Thank you for trying to clarify! The main point of confusion for me, is that when we are calculating the result for Alice, we do a dfs for Bob's turn therefore dfs(not Alice, etc.) - This part quite clear- The problem is when we are doing bob's result and doing the dfs for the following turn (which is Alice) why aren't we doing dfs( Alice) that's where I am still a bit confused
@codertrucker3296
@codertrucker3296 Год назад
@@business_central Because when you are doing bob's result, the current Alice is False, so for the following turn (which is Alice) the Alice has to be True, then you need a (!Alice) to turn Alice to True.
@business_central
@business_central Год назад
@@codertrucker3296 that was my understanding, but when we do that it would be wrong. We have to have dfs(not alice) for both, when next turn is Bob's and when the next one is Alice's.
@NeetCodeIO
@NeetCodeIO Год назад
The not just takes the negation. So not True -> False. not False -> True. This is a pretty trivial feature of any programming language. I would test it out in an ide yourself if you don't believe that it works.
@ayo4590
@ayo4590 Год назад
Hi Neetocde, I was thinking of buying your course but as a broke college student the price is a bit too expensive as a yearly payment. Can you add a monthly payment option? i'll prefer having to pay even more than the current price (like over a year) if the monthly is low enough because i know it's really worth it.
@NeetCodeIO
@NeetCodeIO Год назад
Feel free to email me at neetcodebusiness@gmail
@user-le6ts6ci7h
@user-le6ts6ci7h Год назад
The time complexity you mentioned is not correct, m might at the worst go up to log(n)
@MohddAlii
@MohddAlii Год назад
Why are you minimising at bob's turn, Will bob not play optimally?
@lakshmanvengadesan9096
@lakshmanvengadesan9096 Год назад
Bob is minimizing the score of Alice, not his score
@parashararamesh4252
@parashararamesh4252 Год назад
This is similar to the minimax algorithm so you can refer to that as well. If you think about it the function only returns Alice's maximum value and in that recursion of that function it will be bobs turn as well ( also remember bob is not the starting player). So from Alice's perspective Bob would have to minimise his score for Alice to get the best score. If Bob also maximises his score then it could probably result in Bob having more stones even though he only starts second
@alek4001
@alek4001 Год назад
@@parashararamesh4252 No, they both play optimally. It's just the same thing - minimizing opponents score or maximizing owns. Bob minimizes Alice score == maximizes his own.
@eku333
@eku333 Год назад
@@lakshmanvengadesan9096 Holy shit this comment should be pinned
@johnnychang3456
@johnnychang3456 Год назад
Bob will get Alice's score from the recursive call, of which he'll select the minimum one.
@pilot615
@pilot615 Месяц назад
Now I have just understood!
@AsliArtist
@AsliArtist Месяц назад
Someone ELI5 why at 17:20 we are trying to minimise Alice's score, we are just not including it into the line 21 because the DFS returns BOBS SCORE!!?!?!?! Isnt the DFS returning Alice's score, and if this is the case shouldn't we also be maximising it.???
@adwinsanjo
@adwinsanjo Месяц назад
Since its Bob's turn. Bob tries to maximise his own score and minimises Alice's score as he is playing optimally
@saagerbabung5652
@saagerbabung5652 Год назад
In Google interview, do they accept memorization solution or it has to be only tabulation form for a DP problem?
@twoPointers123
@twoPointers123 Месяц назад
knock knock , is this a Minimax algorithm
@uptwist2260
@uptwist2260 Год назад
Thanks for the daily
@PriyanshuTyagi-ts2uw
@PriyanshuTyagi-ts2uw Месяц назад
Thanks!
@liangyu3771
@liangyu3771 Год назад
life saver. I could not understand the question (sad)
@arnabchatterjee2094
@arnabchatterjee2094 Месяц назад
a typical min max algo kinda tic tac toe ai
@OmarAlimammadzade-v7s
@OmarAlimammadzade-v7s Месяц назад
why we create variable total?
@alphaOrderly
@alphaOrderly Месяц назад
I can't understand problem
@AdamUngier
@AdamUngier Месяц назад
It was my first time experiencing a dynamic programming problem and I am completely and utterly confused, how does your brain think of this stuff?
@vamsikrishnagannamaneni912
@vamsikrishnagannamaneni912 Месяц назад
Good God !
@kotik1221
@kotik1221 10 месяцев назад
Do you have this code snippet somewhere? I want to read the code in my own editor.
@MrKB_SSJ2
@MrKB_SSJ2 Год назад
Yeeeeeeee
@meghasharma_0419
@meghasharma_0419 Год назад
Hey guys I tried to implement this solution in js as follows var stoneGameII = function(piles) { //this problem can be solved using recursion with caching let dp = {} //the dfs has 3 parameters - //alice - to keep track of who is playing alice or bob //i to keep track of index we are at in piles //M defined in problem statement as we can only choose piles between index i to 2M i.e eithier the first pile or the first two pile or first 3 pile so on.... //this function returns the no of stones alice gets const dfs = (alice,i,M) =>{ //Base cases if(i === piles.length) return 0 if((alice,i,M) in dp) return dp[(alice,i,M)] //if it is alice turn we maximize the result , if it is bob's turn we minimize the result(stones alice gets) as both players play optimally let res = alice ? 0 : Number.MAX_SAFE_INTEGER let total = 0 for(let x = 1; xpiles.length) break //we subtract 1 as x begins at 1 and we wanna consider the ith pile too total += piles[i+x-1] console.log(total) //Now we wanna make the dfs call if(alice){ res = Math.max(res, total+dfs(false,i+x,Math.max(M,x))) } else{ //since the function returns alice stone so we do not add bob stones (total ) in case bob is playing res = Math.min(res,dfs(true,i+x, Math.max(M,x))) } } dp[(alice, i, M)] = res return res } return dfs(true,0,1) }; But i m getting wrong answer Can anyone help
@prashantshubham
@prashantshubham Год назад
Issue is with your hash map i.e `dp` implementation
@meghasharma_0419
@meghasharma_0419 Год назад
@@prashantshubham Thanks
Далее
LeetCode 1310 XOR Queries of a Subarray
19:17
Как он понял?
00:13
Просмотров 108 тыс.
How I would learn Leetcode if I could start over
18:03
Просмотров 543 тыс.
Making an Algorithm Faster
30:08
Просмотров 73 тыс.
10 Math Concepts for Programmers
9:32
Просмотров 1,9 млн
Microservices are Technical Debt
31:59
Просмотров 290 тыс.
New 21 Game - Leetcode 837 - Python
19:03
Просмотров 12 тыс.
1140. Stone Game II | DP | LeetCode Daily Challenge
15:47
How to Solve ANY LeetCode Problem (Step-by-Step)
12:37
Просмотров 229 тыс.
Stone Game - Leetcode 877 - Python
22:00
Просмотров 30 тыс.
Unique Binary Search Trees II - Leetcode 95 - Python
12:51