Stone Game II - Leetcode 1140 - Python

  Рет қаралды 23,819

NeetCodeIO

NeetCodeIO

Күн бұрын

Пікірлер: 72
@ary_21
@ary_21 Жыл бұрын
At 11:42 i realised Alice and Bob are playing with me and not with each other
@LasTCursE69
@LasTCursE69 3 ай бұрын
This is by far the most confusing problem I've encountered on leetcode..
@sarwesharivazhagan5085
@sarwesharivazhagan5085 3 ай бұрын
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 3 ай бұрын
Thanks bro
@reckyru
@reckyru Жыл бұрын
DP is pain and makes me cry
@voidpointer398
@voidpointer398 3 ай бұрын
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.
@Antinormanisto
@Antinormanisto 3 ай бұрын
I still don't understand what the hell is going on and what do I do
@TheLearningLab898
@TheLearningLab898 3 ай бұрын
you not alone bro🫂
@satyadheeraj6081
@satyadheeraj6081 3 ай бұрын
@@TheLearningLab898 same here man 🥹
@thunder_cs
@thunder_cs 3 ай бұрын
same
@erickjhormanromero6905
@erickjhormanromero6905 3 ай бұрын
Same
@ParodyCSEDept
@ParodyCSEDept 3 ай бұрын
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 3 ай бұрын
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
@sahilthukral4948
@sahilthukral4948 3 ай бұрын
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
@MP-ny3ep
@MP-ny3ep Жыл бұрын
Phenomenal explanation. Thank you!
@Calypso1406
@Calypso1406 Жыл бұрын
idk how to come up with these kinds of solutions and im genuinely lost
@朴云峰
@朴云峰 Жыл бұрын
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@@朴云峰
@siddhantvishnu4309
@siddhantvishnu4309 3 ай бұрын
Exactly what I had in mind. Just had a few isues coding it up. Great video
@namandubey8348
@namandubey8348 3 ай бұрын
i wonder how long will it me to solve these kind of problem by myself
@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.
@RomanFalcon13
@RomanFalcon13 Жыл бұрын
Thank you king, keep it up!
@lesterdelacruz5088
@lesterdelacruz5088 2 ай бұрын
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.
@dudeyouhavenoidea
@dudeyouhavenoidea Ай бұрын
I am equally confused, after watching stone game 1, I thought we just ignore bob score and only focus on Alices stone
@luizfelipe2330
@luizfelipe2330 3 ай бұрын
For sure this one is one of the best videos that you did.
@user-le6ts6ci7h
@user-le6ts6ci7h Жыл бұрын
The time complexity you mentioned is not correct, m might at the worst go up to log(n)
@mutianzhu5128
@mutianzhu5128 3 ай бұрын
Reminds me of minimax algorithm.
@jaatharsh
@jaatharsh 3 ай бұрын
true saviour, thanks once again
@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
@sheruloves9190
@sheruloves9190 3 ай бұрын
Simply amazing!!
@kotik1221
@kotik1221 Жыл бұрын
Do you have this code snippet somewhere? I want to read the code in my own editor.
@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.
@theman-d
@theman-d 3 ай бұрын
I havethis error "" TypeError: inf is not valid value for the expected return type integer ""
@saagerbabung5652
@saagerbabung5652 Жыл бұрын
In Google interview, do they accept memorization solution or it has to be only tabulation form for a DP problem?
@AsliArtist
@AsliArtist 3 ай бұрын
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 3 ай бұрын
Since its Bob's turn. Bob tries to maximise his own score and minimises Alice's score as he is playing optimally
@pilot615
@pilot615 3 ай бұрын
Now I have just understood!
@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.
@aesophor
@aesophor Жыл бұрын
@@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.
@liangyu3771
@liangyu3771 Жыл бұрын
life saver. I could not understand the question (sad)
@twoPointers123
@twoPointers123 3 ай бұрын
knock knock , is this a Minimax algorithm
@PriyanshuTyagi-ts2uw
@PriyanshuTyagi-ts2uw 3 ай бұрын
Thanks!
@uptwist2260
@uptwist2260 Жыл бұрын
Thanks for the daily
@vamsikrishnagannamaneni912
@vamsikrishnagannamaneni912 3 ай бұрын
Good God !
@arnabchatterjee2094
@arnabchatterjee2094 3 ай бұрын
a typical min max algo kinda tic tac toe ai
@alphaOrderly
@alphaOrderly 3 ай бұрын
I can't understand problem
@AdamUngier
@AdamUngier 3 ай бұрын
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?
@OmarAlimammadzade-v7s
@OmarAlimammadzade-v7s 3 ай бұрын
why we create variable total?
@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
Last Stone Weight II - Leetcode 1049 - Python
19:04
NeetCodeIO
Рет қаралды 16 М.
1140. Stone Game II | DP | LeetCode Daily Challenge
15:47
DeepCodes
Рет қаралды 4,2 М.
The Singing Challenge #joker #Harriet Quinn
00:35
佐助与鸣人
Рет қаралды 44 МЛН
Noodles Eating Challenge, So Magical! So Much Fun#Funnyfamily #Partygames #Funny
00:33
Stone Game - Leetcode 877 - Python
22:00
NeetCode
Рет қаралды 31 М.
Making an Algorithm Faster
30:08
NeetCodeIO
Рет қаралды 147 М.
Leetcode 1140. Stone Game II (game theory)
11:55
LetsCode
Рет қаралды 34
Rotating the Box - Leetcode 1861 - Python
15:14
NeetCodeIO
Рет қаралды 6 М.
LeetCode was HARD until I Learned these 15 Patterns
13:00
Ashish Pratap Singh
Рет қаралды 577 М.
Dynamic Programming isn't too hard. You just don't know what it is.
22:31
DecodingIntuition
Рет қаралды 197 М.
Number of Music Playlists - Leetcode 920 - Python
21:36
NeetCodeIO
Рет қаралды 13 М.
5 Simple Steps for Solving Dynamic Programming Problems
21:27
Reducible
Рет қаралды 1,1 МЛН
The Singing Challenge #joker #Harriet Quinn
00:35
佐助与鸣人
Рет қаралды 44 МЛН