Тёмный
No video :(

Kadane's Algorithm to Maximum Sum Subarray Problem 

CS Dojo
Подписаться 1,9 млн
Просмотров 705 тыс.
50% 1

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

 

22 авг 2024

Поделиться:

Ссылка:

Скачать:

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

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 536   
@larry_in_data1860
@larry_in_data1860 4 года назад
You are such a great lecturer, it took me 1 hour to think about it but ended up with frustration, but you just make me understand within 10 minutes, thank you!
@benjaminsinanovic4123
@benjaminsinanovic4123 Год назад
+1
@UltraB707
@UltraB707 2 месяца назад
Umm you thought for 1 hr helped you understand quicker ig, I'm watching the video 2nd time still no luck...
@yashp1nth
@yashp1nth 4 года назад
according to wikipedia Mr.Kadane came up with the algorithm in less than a minute
@takharamazanpolat7610
@takharamazanpolat7610 3 года назад
Surprised pikachu face
@huaijinruan500
@huaijinruan500 3 года назад
And it took me less than a minute to copy the solution down (and started to think desperately why it should be the case for 2 hours.)
@tejassrivastava6971
@tejassrivastava6971 3 года назад
@@huaijinruan500 same goes for me
@sugaku9455
@sugaku9455 3 года назад
Lek é bravo menor
@salvinantonyvarghese6226
@salvinantonyvarghese6226 2 года назад
😯
@MohdYusufAbdulHamid
@MohdYusufAbdulHamid 4 года назад
This is actually the best explanation of Kadane's algorithm I have seen. I kept asking myself why is this algorithm not very intuitive; with your explanation, it is now.. thanks!
@swapanjain892
@swapanjain892 Год назад
Yeah, exactly.
@benjaminsinanovic4123
@benjaminsinanovic4123 Год назад
@@swapanjain892 +1
@LetsBeHuman
@LetsBeHuman 6 лет назад
5:34 - 8:01 - It differentiates you from other guys. You are the only one here explained why it works. But some how for me, I watched it 4 times and I still don't get it. I will watch it few more times. Edit update: Ok , I got it now.
@dulat1
@dulat1 5 лет назад
It was hard for me to get it too for quite a time but finally I get it. I think what people often confuse is the meaning of max_ending_here. The variable max_ending_here at some index i does NOT mean the maximum subarray sum that can be chosen between 0 and i. It only means the maximum subarray sum that actually ends at that i meaning includes that index i in the end. For example, for an array {2, 3, -7, 1, 2} at the last index which is i=4, max_ending_here is not 5, it is 3. Because it has to END at that index. If you got this then watch the video one more time and it should be clear.
@s510533
@s510533 5 лет назад
Totally agreed with you guys! It took me several times to get it. Thanks again.
@chiranthanmr
@chiranthanmr 5 лет назад
Its like, instead of looking at your life time after living it and finding the best parts by passing through it AGAIN "O(n squared)", you use smaller chunks of your history that you have lived so far and update the best part WHILE LIVING IT. By the time you die, you will know the best part "O(n)". Something to think about: You are already programmed efficient, coz you follow the second way by nature.
@meditationandrelaxationmus741
@meditationandrelaxationmus741 5 лет назад
Truly that' s why we need genius to help !
@fenrir2037
@fenrir2037 5 лет назад
@@dulat1 That makes much more sense now. I was trying to see how he got [1,-3] as [1,-3] instead of just 1 at 2:17. this helps a lot
@huez3n
@huez3n 4 года назад
Summary : The brute force method works by finding the maximum subarrays ending at all n indices and comparing them. Kadane's Algorithm principle, 3:42 : Maximum subarray ending at the (i)th index is either the current element,A[i] or the current element combined with the maximum subarray ending at the (i-1)th index. PS : Just leaving this so I can revise later if needed.
@saurabhverma1381
@saurabhverma1381 4 года назад
You are living in the future, bro.
@Yazan_Majdalawi
@Yazan_Majdalawi 6 месяцев назад
come revise
@AnandKumar-kz3ls
@AnandKumar-kz3ls 5 месяцев назад
thanks buddy
@sushruttabakade6088
@sushruttabakade6088 5 лет назад
I was struggling for hours with this algorithm. Thank you for explaining in such detail.
@genericstospecifics1856
@genericstospecifics1856 3 года назад
You are not alone
@andrefreitas9936
@andrefreitas9936 3 года назад
imagine struggling with Kadane's algorithm 😂
@thejuniordeputy546
@thejuniordeputy546 3 года назад
@@andrefreitas9936 Imagine not able to understand the fact that different people are at different learning phases.
@andrefreitas9936
@andrefreitas9936 3 года назад
@@thejuniordeputy546 That's me :)
@xmangle5382
@xmangle5382 Год назад
@@andrefreitas9936 such mediocre mindset and such big ego
@Monotoss
@Monotoss 3 года назад
I also agree with "5:34 - 8:01 - It differentiates you from other guys" opinion. You are way way better guy than guys who just 'throws code and say it works'. Knowing much doesn't mean one is a great teacher. The one that I admire is the person like you who teaches and explains so well for others to understand easily. Lots of appreciation Man. I hope you upload more of these algorithm explain series
@ovebepari6682
@ovebepari6682 2 года назад
agree
@bin_california
@bin_california Год назад
Appreciate the effort, but i feel this part was obvious (if M > 0, you take M+x, otherwise you take jus x), maybe just because me doing years of leetcode already, lol
@mayankshahabadee8331
@mayankshahabadee8331 3 года назад
Who dislikes such good content, May god give them brains.
@Tubular-Trev
@Tubular-Trev 5 лет назад
You are my hero! thank you for teaching me this stuff. The teachers out here in Kentucky aren't as enthusiastic (university)
@Jonathan-qz9td
@Jonathan-qz9td 4 года назад
Haha which part of Kentucky bro
@Tubular-Trev
@Tubular-Trev 4 года назад
@@Jonathan-qz9td Bowling Green
@anuj4200
@anuj4200 4 года назад
Wow!! you guys are being taught in universities.
@CSERISHINANDHA
@CSERISHINANDHA 3 года назад
@@anuj4200 why you saying so?
@itsahandle
@itsahandle 2 года назад
@@CSERISHINANDHA our unis don't even do that
@jessw4195
@jessw4195 7 месяцев назад
Thank you so much. The way you explain it makes it make so much sense. I could not understand how something so simple worked, but how you explained the principle, the core, of Kadane's Algorithm clicked for me.
@ilyashitchens649
@ilyashitchens649 4 года назад
The explanation is really clear, I've been stuck quite a few hours in solving a problem involving Kadane's algorithme and coudn't visualize it. thanks from France ;)
@maythecodesbewithyou29
@maythecodesbewithyou29 4 года назад
if you have any doubt you can ask me, happy to help a fellow developer
@venkataramanachakravarathu4223
@venkataramanachakravarathu4223 3 месяца назад
This is the true explanation of Kadane's Algorithm. Liked a lot
@egor.okhterov
@egor.okhterov 7 лет назад
You can update max_global in the same way you updated max_current: max_global = max(max_global, max_current)
@gsmdfaheem
@gsmdfaheem 3 года назад
The best kadane's algo explanation ever!!! ❤️
@utkarshmaheshwari7180
@utkarshmaheshwari7180 5 лет назад
Here there is no checks for whether this will take the subarray as contiguous or not... Test with this array:- -2,4,2,-1,5 According to your approach at index 3 it will keep max_current as 6 and at the index 4 the max current will become 11 which isn't correct I guess...
@aaravpatil2725
@aaravpatil2725 5 лет назад
At index 3(where value is -1 in your example) max current will be 5 bcoz max_current = Max(-1, 4+2+(-1)) = 5 and at index 4 the max_current = Max(5,5+5) = 10. check your code the algo works fine.
@dulat1
@dulat1 4 года назад
At index 3, max_ending_here becomes -1. max_current is still 6. Then at index 4, max_ending_here becomes 5. max_current=max(max_current, max_ending_here) which is 6. So no problem
@bsatyam
@bsatyam 2 года назад
I was having such a hard time with this simple problem but you made it so easy! Sleep deprivation is a bitch.
@amarnathprasad9986
@amarnathprasad9986 3 года назад
This is the best explanation I could find on RU-vid. Thank you so much.
@legomgom
@legomgom 6 лет назад
I was working on this problem and didn't understand the core idea until I found your video. Really good job here ! Thanks
@shahlazulkarnine9628
@shahlazulkarnine9628 3 года назад
This made my day, the explanation was so thorough and clear, loved it. Thank you !!!
@PopTropicaInnovation
@PopTropicaInnovation 8 лет назад
Best video about this topic. Easy to understand how the algorithm works and also why it works
@lostnotfoundyet
@lostnotfoundyet 4 года назад
why isn't the max sub array ending in -3, i.e. [1,-3] just [1]?
@Jamie-bh6mg
@Jamie-bh6mg 4 года назад
Because we're looking for the max sub array which ends at -3, so it must include -3. Your answer of [1] is the maximum sub array of [1, -3], but it does not end at -3, it ends at 1
@naturemagics6267
@naturemagics6267 5 лет назад
The best explanation I have ever seen for kadane's algorithm. Thank you. Its really helpful.
@coop4476
@coop4476 4 года назад
max ending at -3 is [1] not [1,-3] because 1-3 = -2 < 1
@aakashavril
@aakashavril 5 лет назад
The best explanation for the maxSubArray question, it's really good that you brought the mathematical proof along with that... :D Really appreciate that.
@hiepxuan2008
@hiepxuan2008 2 года назад
This video is really helpful, I immediately subscribed you!
@dulat1
@dulat1 5 лет назад
For those of you who are still confused, you are most probably missing the meaning of the variable max_ending_here. For example, for an array {-1, 5, -2, 4} when i=2, we are only considering the first 3 elements so far. So the array part we are looking at is {-1, 5, -2}. So what is max_ending_here at this point? It is not 5. It is 3. Because max_ending_here refers to a subarray with a maximum sum that actually ends at that index itself. So the answer is {5, - 2} with sum of 3. So max_ending_here has to END at that index meaning its last element has to be at that index i where you are currently in the loop. If you get it watch the video again and it should be clear.
@dulat1
@dulat1 5 лет назад
By max_ending_here I mean max_current
@pulak727
@pulak727 6 лет назад
Best explanation of maximum sum subarray problem anywhere on the internet.
@atulwaghdhare
@atulwaghdhare Год назад
Kodane's Algo Thank you so much for the explaining. Basically: Brute Force helps but takes a long time. So we choose to find and pick the local maxima among the array while also find the global maxima. By this way we also can get only the global maxima. Man this feels like apply the Maths I learnt as a child
@yasararafathn3283
@yasararafathn3283 4 года назад
I wonder how this type of Algorithms are created.Thats awesome.Optimal solution to Maximum Subarray.Thank u Dojo ji
@dhirajgupta9802
@dhirajgupta9802 3 года назад
concise and clear good work man
@aumkaarpranav8765
@aumkaarpranav8765 2 года назад
just solved a question, that I couldn't do during the contest, using this algo. such happiness and satisfaction!
@sumitbabel5415
@sumitbabel5415 3 года назад
Amazing and simple , clear explanation . Honestly hats off
@TheChesster777
@TheChesster777 5 лет назад
max_current should be initialized at 0, since if say, an array contains [5, 3, -2] and we initialize current_max to be A[0] and we do the current_max = max(current_max, current_max + A[i]) current_max will be 10 instead of 5, and there's no sum that can add to 10 in the array.
@edgarcn
@edgarcn 5 лет назад
It wouldn't happen because the loop begins with the second element i = 1.
@hanxu6346
@hanxu6346 5 лет назад
Thank you for the detailed explanation. It started making a lot of sense when you drew out the values in a table. Though to make it work, I had to initialize my max_current and max_global as 0 instead of A[0]. Subscribed!
@sagart7842
@sagart7842 5 лет назад
Guys if you are getting wrong answers for specific inputs then. Try this: there is small logical error. Consider adding new variable maxcurrent1 inside the function. Initialize it with the max value obtained maxcurrent1=max (a[I] , a[I]+maxcurrent) Which will be compared with maxcurrent. Which is shown to be initialized with a[0]. Only update if maxcurrent1 is greater than old maxcurrent If(maxcurrent1>maxcurrent) { maxcurrent=maxcurrent1; } If(maxcurrent>maxglobal) { maxglobal=maxcurrent; } return maxglobal;
@LetsBeHuman
@LetsBeHuman 6 лет назад
Please do more videos like this. You are our saviour.
@motocomputer
@motocomputer 3 года назад
This is the best explanation I've seen.
@hakkbak
@hakkbak 5 лет назад
It's common sense why Kadane's Algorithm works. If you are picking the maximised "sub-array total" after each element, then there's no 'room' for other possibilities which have a greater sub total (unless the single new element is superior, in which case we take that instead).
@pranaysharma2055
@pranaysharma2055 5 лет назад
what happens for this array [3,2,-1,3,-3].. observe my case below index --- - 1 2 3 local----- 3 5 4 5+3-->which is wrong it should be 4+3 global--- 3 5 5 what happens in such cases?
@julianhaurin9658
@julianhaurin9658 Год назад
@@pranaysharma2055 you add to the local max (4 + 3), not the gobal
@Adrianvdh
@Adrianvdh 6 лет назад
Thank you! If you had trouble understanding the meaning on sub, think of sub_string, where we get a portion of a string by specifying certain indexes of characters we want to extract from the string. The sub array has the same concept.
@ashinzekene
@ashinzekene 3 года назад
Would this work for [-2,3,2,-1,4]?
@youknwmyname1323
@youknwmyname1323 Год назад
You made it so easy to understand. Keep up the good work!
@prateekverma8077
@prateekverma8077 5 лет назад
Man u r so great i couldnt write on my own this algo before watching your vid but after it your algo comes to my mind and i can write it on my own thanks:)
@BlackSammySilkroadOnline
@BlackSammySilkroadOnline 3 года назад
He is basically telling, check if A[i] is largest, make it max_global, if not add A[i] to max_current. In the end, it will be max_global.
@ChintanDaveGhost47
@ChintanDaveGhost47 6 лет назад
You make the problem so easy to understand. Thank you!
@sachinsharma905
@sachinsharma905 3 года назад
Thanks man for the explanation.
@7810
@7810 5 лет назад
The explanation of the Kadane algorithm is quite clear. Thanks for the lesson!
@pranaysharma2055
@pranaysharma2055 5 лет назад
what happens for this array [3,2,-1,3,-3].. observe my case below index --- - 1 2 3 local----- 3 5 4 5+3-->which is wrong it should be 4+3 global--- 3 5 5 what happens in such cases?
@shreevatsalamborghin
@shreevatsalamborghin 4 года назад
how about this? What about this ? O(n) solution without using kadane's algorithm isnt it..? class Solution { public int maxSubArray(int[] nums) { // ans is the final result and currentsum is the sum of current window int ans = 0, currentsum = 0; //intialize the current window to the first element also the final ans currentsum = ans = nums[0]; for(int i=1;i than the existing res then update the current sum if(currentsum + nums[i] > nums[i]) { currentsum+=nums[i]; } //else change the window starting pos to the current element since the result is to be contingous. else { currentsum = nums[i]; } //update largest result after every iteration. ans = Math.max(ans,currentsum); } return ans; } }
@Mrvishalt
@Mrvishalt 4 года назад
Best and most lucid explanation of Kadane's Algorithm! Simply loved it! :) (Y)
@Makwayne
@Makwayne 3 года назад
Honestly, mathematical induction is a "fuck-all" type of reasoning. food for thought. I'm gonna grab a coffee and rewatch till I can't no more.
@fabricator.cap.hill.seattle
@fabricator.cap.hill.seattle 2 года назад
I gave a Thumbs Up for this video. I did not get the proof towards the end of the "Why Does Kadane's Algorithm Work?" section, math proofs aren't my strong point, but I still liked the rest of the video.
@Tuan...
@Tuan... 6 лет назад
I am a grade five and I do not know what the heck is happening right now 😐😐😐😐😐😐😐😐
@blasttrash
@blasttrash 6 лет назад
Start programming early. You can make huge bucks by the time you end high school. You can use that money to buy new games or xbox or play station etc. :P
@ShivamJha00
@ShivamJha00 6 лет назад
blasttrash who would really hire a school kiddo?
@blasttrash
@blasttrash 6 лет назад
You can earn money from programming competitions or hackathons etc. Also there is freelancer or upwork. As a kid, you dont really need money so you can make projects for free at least the first few and then you have a client base to earn money. Also as a kid you can offer cheaper services coz money is not a dealbreaker for you as you have your parents even if you dont get money from your freelancing or hackathons etc. But of course that would take away all the fun of being a kid I guess.
@nishantingle1438
@nishantingle1438 6 лет назад
Don't listen to them kid. Do whatever you like rather than learning programming for money 'cz every other person is for making money in the software industry and no doubt they are making a good sum but to stand out from others you need to have it as your passion. In simple words don't study anything for money, study to improve yourself, to fulfill your hunger of knowledge and curiosity. Don't try to have fake hunger for anything.
@Rengah
@Rengah 5 лет назад
@@blasttrash Hahaha I love how you just translated the ultimate goal to something kids can relate to :) :). "so you can buy more Lego and Lego games on your phone"
@ahmedouyahya
@ahmedouyahya 4 года назад
Thank you sooo much and we would like to see more algorithms in this channel. Again thank you soooo much
@huaijinruan500
@huaijinruan500 3 года назад
Thank you so much! I finally understand this stuff after struggling for 2 hours.
@chrisalvino76
@chrisalvino76 4 месяца назад
very nice. Clear proof, clear code.
@yawar110
@yawar110 5 лет назад
Thanks for posting a very neat explaination (thumbs up for that). I think I might have missed something here... when A = [ 8, -4, 4, 7, -1, -10 ], the code returns 15 as global max, which means its adding 8 and 7 and these two values are not subarray. I was expecting it to return 4 + 7 = 11 as global max. Please correct me if Im wrong.
@raybastienmayol1261
@raybastienmayol1261 5 лет назад
Hello, the sum is 15 because the subarray is [8,-4,4,7]. Hope this still helps.
@ayushagarwal4247
@ayushagarwal4247 4 года назад
@@raybastienmayol1261 A = [1,-2,3,4,-4,5] considering this array as input, the code returns 7 as answee (i.e. [3,4]), but the answer should be 8 (i.e. [3,4,-4,5]. Can you explain me this?
@raybastienmayol1261
@raybastienmayol1261 4 года назад
​@@ayushagarwal4247 Your code might not be checking the last element. Taking the pseudocode in the video and turning it into python, it made sense for me to remove the "-1" in the for statement. So I was using "for i in range(1, len(A) )".
@m.usmansohail2853
@m.usmansohail2853 2 года назад
sub array of first four elements [8,-4,4,7] gives 15. i know its 3 years old but i still wanted to reply lol and i hope you are doing well.
@Enzoerb
@Enzoerb 2 месяца назад
But what about something like: [6, 7, -1, 5, -10]? [6, 7, -1, 5] is the max subarray But [6, 7] sum > [6, 7, -1] sum > [-1] sum And [6, 7, 5] is not a possibility Therefore, wouldn’t I need to compare those 3 things? From the beginning of the max subarray, to X, the current maximum subarray and only X?
@mrkevinlui
@mrkevinlui 4 года назад
This algo does not work. Consider [3, -2, 4, 3, -1], the max sub-array should include the first two elements since they contribute +1. His ending example was a naive [-2, 4, 3, -1] without interleaving positive/negative numbers.
@mrkevinlui
@mrkevinlui 4 года назад
The correct solution was published in the Programming Pearls book, and at stackoverflow.com/questions/3763619/programming-pearls-finding-sub-array-with-max-sum maxsofar = О maxendinghere = О for i = [0. n) { maxendinghere = max(maxendinghere + x[i], 0) maxsofar = max(maxsofar, maxendinghere) } The critical line is the first max() operation within the loop cannot just compare maxSoFar, which is named as max_current in this RU-vid video, against the current newly encountered element. It needs to compare less aggressively against just zero, to accommodate for the case that previous previous numbers could still have positive contribution and cannot be dismissed by just comparing against a[i].
@rossinageorgieva9244
@rossinageorgieva9244 5 лет назад
Great! If I ever get my degree in Computer Science, it will be mostly thanks to guys like you!
@awakashsinha9926
@awakashsinha9926 5 лет назад
😂😂 if I ever is hilarious
@kalyanm6493
@kalyanm6493 5 лет назад
you are a freakin' rockstar!
@hakimalisami
@hakimalisami 4 года назад
Awesome man, you solve the problem with no time.
@nerdygeek7357
@nerdygeek7357 4 года назад
exactly what I was looking for to solve CF - B. Just Eat It! Thank you DOJO
@shashank4577
@shashank4577 4 года назад
Man , Now I'm realizing how you got intoi Google
@Iamine1981
@Iamine1981 4 года назад
thanks for the heads up! I had a similar codility challenge of finding the slices (P,Q) of an array that has minimal average, and finding its index P. I solved it but my performance is still O(N**2), and I believe tweaking your approach can help me lower my runtime to O(N) by using running sums for the average. thanks!
@spicywasab
@spicywasab 8 месяцев назад
Currently doing the selections for france's computing olympiad. Did the first "exam" a week ago, doing the second one tomorrow. I also had something pretty similar, basically removing consecutive values of an array so that the average of the resulting values is the lowest. I found this algorithm a few days ago while I was reading "Competitive Programmer's Handbook" (a free book on the internet). I'm pretty sure I can tweak this solution too, but I know I wouldn't have been able to find it under reasonable time :/
@spicywasab
@spicywasab 8 месяцев назад
(I solved it under O(n^2) the first time, but I'm struggling to understand why Kadane's algorithm works.)
@biplabroy1406
@biplabroy1406 4 года назад
1:34 please explain why brute force solution has the complexity of n^2,,,, In my logic in brute force we are looking in every subset of the set so there are 2^n subsets. Subarray( {a, b, c} ) = (a, b, c, ab, bc, ca,abc) 7 elements... In this logic the order should be O(2^n).. I know there are some mistakes done by me. Please let me know where I doing the mistake.
@rvscharan4100
@rvscharan4100 4 года назад
sub array elements should be contiguous so subarray({a,b,c})=(a,ab,abc,b,bc,c). we do not consider ca as it is contiguous.
@biplabroy1406
@biplabroy1406 4 года назад
@@rvscharan4100 ooohhh right, how I did this mistake😢. Thanks brother.
@elinorkent7188
@elinorkent7188 2 года назад
great video us usual. CS Dojo can explain anything to anyone.
@xTsubasaCrossx
@xTsubasaCrossx 2 года назад
That's why CS Dojo is working at Google and the rest of us at Mc Donalds... Damn you Kadane!
@SanketWaghmare
@SanketWaghmare 4 года назад
For list of length 2 this would provide wrong output. I am sure many must have added this correction in previous comments. The for loop should have range from 1 to len(list)
@ashutoshsinghpatel3686
@ashutoshsinghpatel3686 2 года назад
Sir, it's been a while now since you posted your last video. We all really love the way you teach. Atleast give us a reason for not posting videos anymore.☹
@sskinedGUY
@sskinedGUY 4 года назад
In the for loop it should be i < length(A) not i < length(A) - 1
@bladenjazz
@bladenjazz Год назад
This was very well explained. Thanks for making this video!
@newtonsarr1234
@newtonsarr1234 5 лет назад
You could keep the previous max sum and at each iteration check with previous max sum is positive. If positive, you add it to the current, if negative, you don t add it.
@whzd6745
@whzd6745 3 года назад
there is an alternative optimal solution, it's using prefix sum. You first get the prefix sum array of your given array, and then just subtract the largest with the least. That would take n runtime
@amazingmanish
@amazingmanish 8 лет назад
Neatly explained. Thank You !
@nileshmandlik9662
@nileshmandlik9662 3 года назад
thank you sir . much love from india
@giovannimarazzi8737
@giovannimarazzi8737 6 лет назад
If I'd know the vector have at least one positive number i would do it a little different using 3 subarrays. First I would search for the first number >= 0 and set as first of the "maximum subarray". Next I analise if the next number is positive if yes i add to subarray if not i hold in a "negative subarray" and keep adding to it as i find more negatives. The moment i find a positive number i hold in a "positive subarray" and keep adding to it until i find a negative number. when i have set a negative subarray and a positive subarray i sum them. If they result >=0 then i add both to "maximum subarray". Next only repeat.
@MrTStat
@MrTStat 4 года назад
I still don't get it, someone help me out here even if M is the max what if x is negative? then the sum would be less wouldn't it?
@shreyajindal4685
@shreyajindal4685 4 года назад
exactlyy
@2bitornot2bit73
@2bitornot2bit73 5 лет назад
[-2,3,2,-1,8] vs [-2,3,2,-16,8] will give wrong results: not taking into account the -1 or -16 value before the 8 will give wrong answers (the algo clearly skips the values in between current_max and a[i]) - am I missing something here?
@AnubhavChhabra
@AnubhavChhabra 5 лет назад
Read the algorithm once again. It works fine with both the test cases u mentioned. Cheers :)
@amarjeetverma6965
@amarjeetverma6965 3 года назад
int Kadane(int*A , int size){ int globalSum = A[0], sumNow = A[0]; for(int i=1;i
@suganthiarunachalam9077
@suganthiarunachalam9077 4 года назад
Nice explanation. Good job
@sharpnova2
@sharpnova2 5 лет назад
your code doesn't return 0 if all elements of the array are negative. my solution on codewars: var maxSequence = function(arr){ var runningMax = 0; var maxEndingHere = 0; for (var i = 0; i < arr.length; i++){ maxEndingHere += arr[i]; if (maxEndingHere < 0) maxEndingHere = 0; if (runningMax < maxEndingHere) runningMax = maxEndingHere; } return runningMax; } returns 0 (empty sub-array) if all elements are negative.
@sharpnova2
@sharpnova2 5 лет назад
also it is more efficient because there are less comparisons. (no invocation of max/min)
@Maxhsynv
@Maxhsynv 7 месяцев назад
I'm still confised about intuition behind it. You just directly started asking "what is maximum sub-array ENDING at this index?", but what I was thinking before was "what is maximum sub-array STARTING at this index?" which took me to wrong approach. So what is the reason behind it?
@sourashismondal5060
@sourashismondal5060 3 года назад
You described the recurrence relation , but what if the max subarray of the smaller sub problem is not he last part of that sub problem , instead it is somewhere in the middle of the subproblem . I dont understand how this algorithm is DP . Because if I try to solve it recursively, there is no overlapping subproblems. If anyone knows , please feel free to explain :)
@bladenjazz
@bladenjazz Год назад
This is one year later but I believe what you need is this. At each step of the algorithm you are deciding what is the max sub array that ends at the current index. As he said, it will either be the current index only, or the precious index's max sub array plus the current index.
@hil449
@hil449 Год назад
i think you meant 'if its in the middle of the array'. If the best is in the middle we're gonna find it during the for loop and we're gonna combine it with the best subarray sum to its left. Btw this is not a dp problem, this is greedy imo because you can solve this problem using prefix sum and a greedy approach
@normalkpopstaner630
@normalkpopstaner630 4 года назад
Thank you sooo much . I was really confused before .thanks for clearing my doubt . Thank youuuuu soooo much
@bigo2012
@bigo2012 Год назад
I solved that code problem by myself with the brute force solution at first, I thought I was pretty smart haha
@rockingbeast3651
@rockingbeast3651 4 года назад
i think mine one is also taking O(n) int maxSubArray(vector& nums) { if(nums.size()==0) return 0; int i=0,sum=0,New=0,j=0; while(i
@mdmesbahurrahman7311
@mdmesbahurrahman7311 3 года назад
great tutorial! take love from bangladesh!
@narendrakumariitb
@narendrakumariitb 3 года назад
Thank you. Best Explanation
@TheChilllin
@TheChilllin 3 года назад
It does not work with [1,2] does it cuz both var are initialized at 1 and the progression makes it go up to 4, or am I going crazy lol
@omerbahat5408
@omerbahat5408 3 года назад
You've explained it perfectly, thank you so much man!
@seal0118
@seal0118 3 года назад
he used contradiction to prove the algorithm, if you have a small background on proof techniques you can easily understand what he is talking about . also its a very easy and intuitive algorithm, i dont know why many people dont understand it...
@ogedaykhan9909
@ogedaykhan9909 2 года назад
what is tx what is mx. It makes a basic topic so complicated. Just use sample numbers
@shat104
@shat104 5 лет назад
my biggest problem is understanding the question due to certain terminology. anyway this made things easy.
@rishabhkothari1763
@rishabhkothari1763 3 года назад
How would the modified code look like if we wanted to display starting and ending index for the given subarray as well ? Btw Loved the Explanation!
@baiano360
@baiano360 2 года назад
old question but something like this is working for me, where (l)eft and (r)ight are the starting and ending indexes. def maxSubArray(nums: List[int]) -> List[int]: curSum, maxSum = 0, -inf l, r = 0, 0 for i,n in enumerate(nums): if n > curSum+n: curSum = n l = i else: curSum += n if maxSum < curSum: maxSum = curSum r = i return [maxSum, l, r]
@jiango
@jiango 2 года назад
@@baiano360 Your code doesn't get the correct indices. For example on test case: [5, 4, -1, 7, 8] Your code returns 0 as start index, and 3 as end index. The expected should be 0 as start, but 4 as end. (The max subarr is the entire input array; sum = 23)
@geldelian
@geldelian 7 месяцев назад
It says that sum(T) sum(M) = -100. I don't get it
@heginiojrtaeza4187
@heginiojrtaeza4187 2 года назад
awesome explanation. thank you!
@nikhilbhujbal8927
@nikhilbhujbal8927 4 года назад
Very nice explanation 🤘
@artemsvobodin728
@artemsvobodin728 4 года назад
Very clear explanation
@PianoOfSouls21
@PianoOfSouls21 8 лет назад
Awesome video!! Thank you so much for creating this. It really helped me in understanding this problem.
@maythecodesbewithyou29
@maythecodesbewithyou29 4 года назад
if you have any doubt you can ask me, happy to help a fellow developer
@II_xD_II
@II_xD_II 4 года назад
plz more video about commonly used algos it will help me a lot
@nguyenchau7107
@nguyenchau7107 3 года назад
Who are here, after trying to solve the codeWar problem?
@BeardedBong
@BeardedBong 3 года назад
excellent explanation..thanks a lot
Далее
When I met the most famous Cristiano
01:03
Просмотров 24 млн
ОБЗОР ПОДАРКОВ 🎁 | WICSUR #shorts
00:55
The hardest problem on the hardest test
11:15
Просмотров 15 млн
Google Coding Interview With A High School Student
57:24
How Dijkstra's Algorithm Works
8:31
Просмотров 1,3 млн
LeetCode was HARD until I Learned these 15 Patterns
13:00
Sliding Window Technique - Algorithmic Mental Models
36:45
Fast Inverse Square Root - A Quake III Algorithm
20:08