Kadane's Algorithm - Maximum Sum Subarray (Amazon Coding Interview Question)

Поделиться
HTML-код
  • Опубликовано: 30 сен 2024

Комментарии • 296

  • @chrishamilton1728
    @chrishamilton1728 4 года назад +389

    Samsung: "Try to find the maximum sub-arr-"
    Me after watching Nick White: "Yo, you're coming at me with this weak crap?"

  • @brah2K
    @brah2K 4 года назад +148

    12:56 “people will say...” cuts the video and corrects the variable name lol

    • @NickWhite
      @NickWhite  4 года назад +27

      hahahahaha

    • @Frederic_Chopin.
      @Frederic_Chopin. 4 года назад

      Lmao

    • @josiahroa177
      @josiahroa177 4 года назад +7

      Was wondering what was gonna happen when he went to run the code lol

    • @MariyamVlogs707
      @MariyamVlogs707 4 года назад +1

      @@NickWhite use a visual platform how each line of code executes programme because many are suffering how logic internally works

    • @punstress
      @punstress 4 года назад +1

      Which variable, I don't see it?

  • @mgtowindia9549
    @mgtowindia9549 4 года назад +46

    I like to watch your videos while taking dump every day at 1 pm as it helps to build the pressure in my abdomen.

  • @quinn479
    @quinn479 3 года назад +255

    Fun fact - Jay Kadane came up with this algorithm in under a minute after other researchers spent months working on different solutions.

    • @daruiraikage
      @daruiraikage 3 года назад +42

      that a lie innit, he well nicked the idea off of me uncle jamaal

    • @rahulbalan
      @rahulbalan 3 года назад +33

      Those other researchers is me.

    • @ButerWarrior44
      @ButerWarrior44 3 года назад

      wow what a nerd. shit took me 3 hours 🤓🤓

    • @Nivek4g
      @Nivek4g 3 года назад +66

      Researchers spent months while interviewers expect 30 minutes lmao.

    • @saurabhraj5772
      @saurabhraj5772 2 года назад +10

      But the irony is interviewer expect in 25 minutes with production ready code. So if you don't know algorithm in advance then very difficult to crack and if you know then anyone can solve in 10 minutes.

  • @kevintran7085
    @kevintran7085 4 года назад +16

    Hey Nick, I watched all of your LeetCoding videos to help me prepare for my technical interviews. I was able to secure two offers from big tech companies (including a FAANG). I just wanted to thank you for making these videos and helping people like myself achieve their professional goals!

    • @abhi.r8
      @abhi.r8 3 года назад +1

      He teaches in which language and u wrote code in interviews in which language ??

    • @g.deepakkrishnaa3847
      @g.deepakkrishnaa3847 2 года назад +1

      @@abhi.r8 he teaches in JAVA and I don't know about the second question

  • @krishcan4727
    @krishcan4727 4 года назад +35

    The actual kandane algorithm explanation starts at 6:50

  • @kimsung2384
    @kimsung2384 4 года назад +47

    This guy rocks! I love his videos and explanations. I’ve been in the programming space for 21.5 years but I don’t get bored of listening to Nick White. He’s intelligent, enthusiastic, innovative and has excellent problem solving skills. This is the guy I’d like in my team.

  • @justaguy2247
    @justaguy2247 4 года назад +69

    Gave you a like just to help, and this comment is also for the algorithm.

  • @xavier2586
    @xavier2586 2 года назад +2

    I think you made a typo in line 6. curr is not defined.

  • @tanishktripathi8773
    @tanishktripathi8773 3 года назад +13

    Hey Nick!
    Many students from India just like me watch your channel and learn logics with very easily readable code.
    I just want to tell you that you are doing a great job and please keep the videos coming Everybody enjoys your video not just because you solve the problem but because you solve them with a lot of ease and fun.

  • @elementalneil7967
    @elementalneil7967 3 года назад +1

    He calls the O(n^2) solution brute-force. The first solution I managed to come up with was O(n^3). Fml.

  • @abhi4unme2002
    @abhi4unme2002 2 года назад +1

    Hey Nick you forgot to change the cur to curr_sum at line 6. Btw, nice explaination.

  • @lazyto12
    @lazyto12 2 года назад +1

    Solution method/function is off. Try input array = {-2,2,5,-11,8,6,-7,10}. At 7th iterating;- current_sum = max(current_sum + arr[7], arr[7]). the result is current_sum + 10 = 14 + 10 = 24. Result should be 14

    • @seanli188
      @seanli188 3 месяца назад

      No, it is not, according to the algorithm, your current sum at 7th iteration is 8+6+-7 which is 7, 7+10 is 17 which is the new Max sum

  • @yakinwissem8665
    @yakinwissem8665 4 года назад +13

    your content is amazing, its way too good to be true

  • @doopian
    @doopian 4 года назад +6

    I normally lurk, but ill give you a like and post this comment since you've helped me learn a lot :)

  • @jamesyoo67
    @jamesyoo67 4 года назад +23

    This is the BEST channel for learning algos and interviewing .

  • @sandhyareddy7349
    @sandhyareddy7349 2 года назад +3

    Line 6: wth is cur???

  • @josiahroa177
    @josiahroa177 4 года назад +5

    Dropping a like and a comment. This channel deserves so much more attention

  • @ashwinishanbhogue2917
    @ashwinishanbhogue2917 4 года назад +6

    Your videos are the best! I’m preparing for a job switch and learning ds & algorithms, nobody explains the things like you do. Thank you so much for helping us out! Keep doing the good work!

  • @animeshnaik2345
    @animeshnaik2345 3 года назад

    Nick white... litterally very white!!...I must say!...kidding...nice explanation..thank you very much!!👍

  • @adammarez857
    @adammarez857 22 дня назад

    I subscribe to practically no one. I almost like no one. I love your page. Great job. I liked bro. You remind me a young Michael Anthony Hall.

  • @parthsalat
    @parthsalat 3 года назад +1

    Where is codesignal's link?

  • @adil6873
    @adil6873 4 года назад +4

    Hey..Can you please continue your "Technical Interview Study Guide" series,it's quite helpful.

  • @Luna-vk9xy
    @Luna-vk9xy 4 года назад +3

    I've been trying to find a proper explaination for this algorithm for a day now and I finally understand how it works. Thank you so much

  • @tathagatnegi5923
    @tathagatnegi5923 4 года назад +2

    Sir can you make a video on how to calculate time and space complexity . Like i have seen many videos but still. For ex- take 1 example of all sorting techniques and tell us how to find time complexity and you can even modify the sorting technique and show us the new complexity....it will be of great help sir🥺

  • @louis-hz4up
    @louis-hz4up 4 года назад +2

    Hi Nick, i have a short Question: Is the Steem Account "iwudah" belongs to you and do you have recently published this Video here on the Steem Platform? Thanks in Advance - greetings, louis

  • @abc123evoturbobonker
    @abc123evoturbobonker Год назад

    Line 5 should be `inputArray[i] + inputArray[i-1] surely?? in the case of [-2, 2, 5, 20, 6, -5, 8] your code will return 36????? or have I lost my mind?

  • @prathyushakadali3330
    @prathyushakadali3330 3 месяца назад

    Hi Nick, Thanks so much for sharing this. QQ: Shouldn't max_sum be equal to zero initially?

  • @lokeshrajselvaraj5288
    @lokeshrajselvaraj5288 2 года назад +1

    NIT - Magic at 12:58. Line#6 , cur became current_sum on click run tests. Just for fun (or i did not understand your sarcasm). Your videos rock.
    Going back and explaining how we lost -2 and started over with 2 is amazing.

  • @pradyothcherry3426
    @pradyothcherry3426 4 года назад +1

    There is slight Correction in this code!
    Initialize:
    max_so_far = 0
    max_ending_here = 0
    Loop for each element of the array
    max_ending_here = max_ending_here + a[i]
    if(max_ending_here < 0)
    max_ending_here = 0
    if(max_so_far < max_ending_here)
    max_so_far = max_ending_here
    return max_so_far

  • @luckyismynickname
    @luckyismynickname 4 года назад +3

    Amazing man please please do more videos like that. I appreciate your hard work on this. Keep growing brother 😊😊😊

  • @JohnSmith-xf1zu
    @JohnSmith-xf1zu 3 года назад +2

    Damn. I was going though Priority Queues similar to a Huffman encoding tree combing Max Sum pairs into new nodes and leafs, but your solution was much easier. Nice work!

  • @kushalbaldev8490
    @kushalbaldev8490 4 года назад

    Hope that helps more to understand just added comment to the code to dry track.!!
    int [] array= {-2,2,5,-11,6};
    int max_sum=array[0]; //i.e -2
    int current_sum=max_sum; //i.e -2
    for(int i=1;i

  • @yiyaoran8637
    @yiyaoran8637 7 месяцев назад

    I spent 7 hours (whole night) reading the textbook and watching RUclips trying to understand this. Was about to give up my college until i saw this video.

  • @kamaleshananthapadmanabhan1573
    @kamaleshananthapadmanabhan1573 4 года назад +2

    5:21 Shouldn't it be O(N^3) because you are taking the sum of the subarrays?

  • @davidjames1684
    @davidjames1684 3 года назад

    Another badly worded question... contiguous can mean "sharing a common border", and border can have a meaning of "the edge or boundary of something", so just add up all the positive integers and we are done. The entire array is bounded by the lowest and highest indexes, thus we can pluck any of [-2, 2, 5, -11, 6], because from the definitions, they are bounded by both the lowest and highest indexes (0 and 4), and also bounded by brackets, thus ANY subset is still contiguous by definition. I pick 2 + 5 + 6 = 13. This guy said you cannot do that but I disagree because even doing that matches the definitions. I can start on Monday FB.

  • @anuragsandhu9590
    @anuragsandhu9590 4 года назад

    Code in Javascript:
    function findMaxSubArray(ar) {
    let currentSum = ar[0], maxSum = ar[0], index = 1;
    while (index < ar.length) {
    currentSum = ar[index] < (currentSum + ar[index]) ? (currentSum + ar[index]) : ar[index];
    if (maxSum < currentSum) maxSum = currentSum;
    index++;
    }
    return maxSum;
    }

  • @prakashkrishna2566
    @prakashkrishna2566 2 года назад

    class Solution {
    public int maxSubArray(int[] nums) {
    int curr_sum = nums[0];
    int max_sum = nums[0];

    for(int i=1;i

  • @deadelinor
    @deadelinor 3 года назад

    I tried watching 2-3 other videos but my dumbass brain could only understand this explanation. Great job!

  • @ed2023bc
    @ed2023bc 4 месяца назад

    You're too fast when explaining the core of this logic. I don't understand why people do it. It's not a race.

  • @dr4kk0nnysinc59
    @dr4kk0nnysinc59 3 года назад

    Bro, I was watching this video for lunch, and the next leet code problem I did was exactly this one, what in the flying fuck

  • @somewheresomeone3959
    @somewheresomeone3959 2 года назад

    Hi there, thanks for the video, but when I submit the code following the ideas, the leetcode gives me a special case, when length of the array = 1, for example, then the output will be 2, so better get the length checked before the loop.

  • @expansivegymnast1020
    @expansivegymnast1020 2 года назад

    I got this problem in my Amazon internship OA. Totally messed it up. Learned from my mistake.

  • @damodaranm3044
    @damodaranm3044 4 года назад

    consider your viewers are first grade kids. dont skip what u are about to explain . dont think "like u know what i mean" while u teach something . Pls finish off the exaplaination . dont give examples while u teach give a clearcut full length explaination that what people wants or else theres no use makes tons of videos .espically in this video 4.59 u are are about to say something but u literally just skipped . see nick not everyone are genius like u . however i liked the video

  • @MikeLeed
    @MikeLeed 2 года назад

    I was on the fence about giving that like he asked for, but the little plug in 5:38 cemented it, liked from me, all day everyday, fuck yea for Nick White.

  • @yehuditeshel2537
    @yehuditeshel2537 3 года назад

    I solved it like this - also linear time. good?
    int main()
    {
    int array[NUM] = {-2,2,5,1,1,-11,6,5,4};
    int i;
    int max=0;
    int tempsum=0;
    for (i=0;i

  • @ziakhan-tk7rk
    @ziakhan-tk7rk 3 года назад

    This doesn't look like an easy problem that can be solved within 45 mins. How are such questions asked in interview?

  • @yugioh8810
    @yugioh8810 4 года назад

    interviewer: can you find a linear solution?
    me: hell yeah bitch I watch Nick White, now whose your daddy?

  • @easysolutions135
    @easysolutions135 3 года назад

    Bro...!!! You deserve lot more than ...likes. I have shared your video ...with my mates.

  • @mertciflikli
    @mertciflikli 2 года назад

    Instead of current_sum, it should definitely be named as current_max_sum to be more understandable.

  • @gajendrasonare
    @gajendrasonare 3 года назад

    I used this technique to solve a problem and then I came to know this is technique has a name "kadane's algorithm".

  • @FilthySnob
    @FilthySnob 4 года назад

    i don't understand why are you using the math library for comparing the max sums instead of normal conditions ??? just to show off or there is a legit reason?

  • @rajankhatri3388
    @rajankhatri3388 4 года назад

    Print the sub array with the indexes.
    public static void printMaxSumSubArray(int[] nums, int length) {
    int max_sum = nums[0];
    int current_sum = max_sum;
    int start=0;
    int end=0;
    for(int i=1; i nums[i]) {
    end = end + 1;
    current_sum = current_sum + nums[i];
    }
    else {
    current_sum = nums[i];
    start = i;
    end=i;
    }
    max_sum = Math.max(current_sum, max_sum);
    }
    System.out.println("Start index:"+start+", End index:"+end);
    for(int i=start; i

  • @spaghettipupper9901
    @spaghettipupper9901 3 года назад

    Lol I like how right before he runs to code to show that it works he jump cuts to it passing after he changed cur to current_sum at 12:55

  • @theb1rd
    @theb1rd 4 года назад +5

    I was asked this in a coding interview recently. Pretty difficult to solve on a whiteboard, with limited time, and an audience. It wasn't pretty.
    I've been programming professionally for 25 years (principal level) - personally, I would never subject a candidate to this, and I question the wisdom of these sorts of interview problems. More than likely, they're selecting people who've seen a lot of interview problems, not necessarily good programmers or problem-solvers.
    I muddled through, with a few hints. It was one of the most stressful interview questions of my career. (Got the offer, didn't take it.)
    Interviews suck.

    • @jagaya3662
      @jagaya3662 4 года назад

      Well it's easy for them to do. Just pick one well established algorithm, design a question around it and see if people know it... I mean, the thing has a name, making it sound like someone quite knowledgable had to come up with the idea - not that it is common knowledge with which people came up on the spot.

    • @dijoxx
      @dijoxx 4 года назад

      Just because you've been doing it for 25 years with a bloated title doesn't mean you're actually good at it. You can surely find some mediocre companies to work for, but the best ones will want someone better. Sorry to hear about your experience.

    • @harshitanailwal7016
      @harshitanailwal7016 2 года назад

      @@dijoxx i don't think you read her whole comment! there is no need to be mean!

  • @kamakshitrivedi8561
    @kamakshitrivedi8561 3 года назад

    If this question is changed to maximum possible sum of alternate elements and display the sum.

  • @krishna100982
    @krishna100982 4 года назад +3

    Did you apply for SDE at Amazon, seems like you know more than enough to get in.

  • @lakhbawa
    @lakhbawa 2 года назад

    hell, yeah, i have been watching white's video, so i can come up with linear run time solution :p

  • @junehaoching6095
    @junehaoching6095 4 года назад +3

    Love it! I found gold when I found your channel!
    Tried with several cases, with the methods you taught, how can we return the index of the subarray as well?

    • @0x6e95
      @0x6e95 4 года назад +1

      You could try keeping two pointers m and n for returning the indices of the subarray. We would update both m and n whenever we find a cur_sum that beats our max_sum and starts a new subarray sum (i.e current element > cur_sum). We would update only n if our cur_sum beats out our max_sum and we don't start a new subarray sum.

  • @umamaheshsukamanchi
    @umamaheshsukamanchi 3 года назад +1

    Great explanation

  • @lily_h-m7j
    @lily_h-m7j 2 года назад

    Cutest coding teacher on RUclipseee 💗
    I mean best. Best. ☺️

  • @danielcaligiuri5382
    @danielcaligiuri5382 4 года назад

    not sure why this is such a common question. very difficult o(n) time unless you've memorized it

  • @valentinmorales2633
    @valentinmorales2633 10 месяцев назад

    Here is your like good man, excellent explanation!

  • @anonimettalontana4944
    @anonimettalontana4944 2 года назад

    Liking before even watching! Thanks, man!

  • @rockyisabroad
    @rockyisabroad 4 года назад

    What's the software you're using to shoot these videos and move the arrows around and what not?

  • @theaveragecoder6182
    @theaveragecoder6182 3 года назад

    74 -72 94 -53 -59 -3 -66 36 -13 22 73 15 -52 75
    Does'nt work on this test case .

  • @yashp1nth
    @yashp1nth 4 года назад +1

    According to wikipedia Mr.Kadane came up with the algorithm in less than a minute

  • @conorhynes8633
    @conorhynes8633 4 года назад

    you'll get more likes if you explain the your approach

  • @krishnajithk9322
    @krishnajithk9322 3 года назад +1

    Your way of explaining things is awesome brother... 🔥

  • @faisalabuzour8504
    @faisalabuzour8504 2 года назад

    cur is not defined anywhere. I guess you meant current_sum

  • @jjchoi08
    @jjchoi08 4 года назад +1

    Thanks for this video! Is knowing bruteforce and Kane's aglo enough for this problem? Would interviewers usually ask to solve this in different approach like divide and conquer?

  • @tathagatnegi5923
    @tathagatnegi5923 4 года назад +4

    You are the best❤️

  • @sitimartoon2521
    @sitimartoon2521 Год назад

    Good Screening Explanation...Keep it up

  • @samandarboymurodov8941
    @samandarboymurodov8941 3 года назад +1

    thank you, Nick. It is very well explained

  • @suryakumar1511
    @suryakumar1511 4 года назад

    Can you please help me identify max array permutations

  • @ankitsharma3490
    @ankitsharma3490 4 года назад +1

    Can we also solve it through recursion? Essentially breaking down arrays into two parts and returning max among them. Base case would be array size 1.
    1) Array including first index and excluding last index
    2) Array excluding first index and including last index

    • @swagatikachoudhury2115
      @swagatikachoudhury2115 2 года назад

      yes, I tried the same approach....It will work but I got TLE for some of the test cases.
      PFA:
      class Solution {
      public int maxSubArray(int[] nums) {

      int total=0;
      for(int i=0;i

  • @putthetrust
    @putthetrust 4 года назад +1

    People should be liking your videos a lot because you are putting this content out for free... Thanks for all the help

  • @etherioussanjudraganeel3163
    @etherioussanjudraganeel3163 3 года назад

    Lol the introduction is pretty straight forward

  • @pauls60r
    @pauls60r 4 года назад +1

    This is the clearest explanation of Kadane's Algo I've seen thus far

  • @rubinip1956
    @rubinip1956 4 года назад

    How to get that subarray…. i.e (2,5)

  • @antianti4331
    @antianti4331 2 года назад

    Nice representation of dynamic programming

  • @nayyyhaa
    @nayyyhaa 3 года назад

    LOVE THISSS💯

  • @TechiiEngineer
    @TechiiEngineer 4 года назад

    I liked n going to comment each video don't worry

  • @believeandreceivedmyhusban3005
    @believeandreceivedmyhusban3005 3 года назад

    Hey hey hey my love 💓 how is your mood right now .....

  • @ByteMock
    @ByteMock 4 года назад +3

    Great question - we will ask this one soon. Thanks for the idea!

  • @dibyajyotisarkar5288
    @dibyajyotisarkar5288 4 года назад +2

    Wow! Thank you very much for the detailed explanation it really helped.

  • @dr.darkfurygaming9174
    @dr.darkfurygaming9174 4 года назад +1

    Liked it

  • @rajendrahiray1555
    @rajendrahiray1555 3 года назад

    You change the variable name before run 😂

  • @dishagupta7446
    @dishagupta7446 4 года назад +1

    Awsm teacher

  • @MuhammadAhsan-hq2bc
    @MuhammadAhsan-hq2bc 4 года назад

    i hit the like button for my man ; Nick White!

  • @rchukkapalli1
    @rchukkapalli1 4 года назад +1

    Watch a lot of videos and will do "like". you are doing an amazing job and I am learning a lot.

  • @SHSelect
    @SHSelect 2 года назад

    because I watch Nick Whites videos

  • @naveennoel9496
    @naveennoel9496 4 года назад +2

    I love the energy and confidence. It boosts up one's coding brain :)

  • @maxdegreat566
    @maxdegreat566 2 года назад

    Is line 6 an error? i think its meant to be currentsum not curr

  • @madhavtibrewal6614
    @madhavtibrewal6614 4 года назад

    There is an array denoting numbers of n different types of candies.
    A person is happy if he receives n-1 different types of candies.Find maximum no of persons who can be made happy.
    Sample:-
    3 //size of array
    7//Freq of first type of candies
    3//freq. For second type
    12//Freq. For 3rd type
    Output:- 10
    Since we can distribute 7 pairs of {1st and 3rd type} and 3 pairs of {2nd and 3rd type}
    Please help me with this.
    I think this is a problem related to permutations and combinations but I really cannot figure it out..

  • @CaseyCarroll42
    @CaseyCarroll42 4 года назад +4

    Love your vids! Correct me if I'm wrong, but I believe your solution contains an error. The max sum and the current sum should be initialized to 0, not the first item in the array. Otherwise, line 5 will evaluate Math.max(-4, -2) instead of Math.max(-2, -2). I noticed this when I ran your solution against the same array, but with a positive 5 inserted at position 0: [5, -2, 2, 5, -11, 6]. The max sum came out to 15, which is incorrect.

    • @pradyothcherry3426
      @pradyothcherry3426 4 года назад +2

      I was searching for this comment..!

    • @benmatt8940
      @benmatt8940 4 года назад +1

      I came back to see this comment all the others are just fanatics and didn't even try his solution, I really think he needs to update this video because many are just followers...

    • @oluwatoyinamushan965
      @oluwatoyinamushan965 2 года назад +1

      It's been ages but for those who would read this today, Nick is actually right. Both Current sum and Max sum should be initialized to the first item in the array. And the for loop would begin from index 1.
      Line 5 would evaluate to Math.max(0, 2) not Math.max(-4,-2) nor Math.max(-2,-2), thus everything would work well. Even trying the sample array you gave with his code, the result was 10 which is technically correct so maybe there was a typo(you most likely initialized your i in for loop to 0 not 1) or different logic in your code.
      Forgive me if his video has been updated and earlier he used 'var i = 0' but has now changed it to be 'var i = 1'. If his video/code has been the same since you made this comment, then he has always been right.

    • @DeathEater93
      @DeathEater93 Год назад

      The for loop should start with i = 1, if you start it with i=0, you get 15 which is wrong.

  • @ItchyClover
    @ItchyClover 4 года назад +1

    Let's help with that RUclips algorithm

  • @konradonbal2020
    @konradonbal2020 4 года назад +1

    At long last! I am watching your videos for couple months and finally when I saw your new video I said: nah, i know that, no need to analyze this :D

  • @rohit_ojha
    @rohit_ojha 3 года назад

    please make more videos on DSA......

  • @raj22kesh
    @raj22kesh 3 года назад

    I like this Nick White's explanation. He is precise simple and short. He is not boring explanation like others who takes 30min explanation on every small topics. When you are on the flow and need some hints. You wouldn't like to listen to 30-40 min boring explanation.