Kadanes algorithm | Longest sum contiguous subarray

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

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

  • @YisName
    @YisName 4 года назад +90

    I have seen several explanations. But this one is best.

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

      Thanks :)

    • @RudraSingh-pb5ls
      @RudraSingh-pb5ls 4 года назад +6

      I don't think so ! He explained the algorithm in a good manner but that's rote learning.

    • @RudraSingh-pb5ls
      @RudraSingh-pb5ls 4 года назад +5

      He should have told us how that algorithm was built on what mathematical basis Kadane got the intuition for this problem and developed an O(n) solution

    • @anjalisingh-sx5ct
      @anjalisingh-sx5ct 4 года назад +1

      @@RudraSingh-pb5ls intuitive approach would be for each element compare it with all the elements on its right side.. (2 for loops)...add them if(sum>0)...this would take 0(n^2)
      Which is very similar to kadane algo(we taking 2 pointers one for adding the elements and other for finding the longest subarray sum)is similar to this n reduce the runtime...

    • @RudraSingh-pb5ls
      @RudraSingh-pb5ls 4 года назад +5

      @@anjalisingh-sx5ct I know what is kadanes and how it works but the way you guys are explaining is the worst. You just telling me how to do instead of why ?
      So the question isn't how , question is why !

  • @Ilovechess48
    @Ilovechess48 Месяц назад

    Best explanation on RUclips, thank you so much!

  • @alexpadilla5741
    @alexpadilla5741 3 года назад +62

    The variable names make it more confusing than it needs to be (at least for me it did), renaming to sum & result would make it easier to understand.
    Sum keeps track of max (sum of prev numbers + curr or curr by itself). And then result just keeps track of the largest sum you’ve encountered.

  • @PrafulPrasad
    @PrafulPrasad 6 месяцев назад +1

    Dudeee I have scraped the entire internet to understand this algo and till now yours was the best, I have completely understood it now, you have not overcomplicated things or undercomplicated it to make it seem tad easy, you have kept the difficulty just perfect.

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

    When you are so bored coding that you name your variable 'meh'

  • @Usurperhk
    @Usurperhk 4 года назад +8

    Best explanation of Kadane's algorithm, Good job TECH DOSE!!!

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

    Super video! I applauded for ₹40.00 👏

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

      Thanks for your support :)

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

    This is my favourite RUclips channel for Coding along with mycodeschool.

  • @ganesh_130
    @ganesh_130 3 года назад +3

    Thank sir I have learnt whole DSA with strong understanding from your channel

  • @rohiteshkumarjain7772
    @rohiteshkumarjain7772 4 года назад +65

    Although you have only 12.2 k subs, pls don't stop making videos, have patience and keep making such videos, it will take time but you will surely reach 1M subs soon. Don't stop, if you feel your videos are not making money, make videos as a charity to the students.

    • @techdose4u
      @techdose4u  4 года назад +66

      Sure man :) Even though I don't earn much through RUclips, but by making videos I get to learn as well. Also, teaching is my hobby. So, I will continue :)

    • @AdityaRaj-bn3ht
      @AdityaRaj-bn3ht 4 года назад +3

      @@techdose4u You have helped me a lot. You explain the topic very well. Hats off man for your effort.

    • @nishant5249
      @nishant5249 3 года назад +3

      @@techdose4u thanks sir please keep going... we need your videos

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

      @@techdose4u And here it goes...... You`ve now 65.6k subscribers :)

    • @techdose4u
      @techdose4u  3 года назад +7

      Stay connected with us ☺️

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

    Magnificent implementation of Algorithm..!!
    Keep it up👍

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

    Great explanation, I was going round and round many videos since last 2 hours. Finally got it

  • @riteeshbommaraju
    @riteeshbommaraju 3 года назад +6

    Beautifully Explained !! The best explanation of Kadane's Algorithm !! Keep it up mate !!

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

    The best explanation of Kadanes Algo!!

  • @theyoutubespecialist9004
    @theyoutubespecialist9004 3 года назад +17

    Trust me buddy, there can't be a better explanation than this! ❤️

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

    Hi,
    Can you please explain the thought process behind the solution? I mean how did you come up with 'msf' and 'meh'? A detail explanation behind the intuition will be helpful.

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

      MSF - Max So Far
      MEH - Max Ending Here

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

      @@vitaliitomas4057 I know that.

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

      if we add have a running sum rs and we claim its part of the maxsum sub array then if we add b :rs+b = maxsum but we notice that maxsum is less than b then rs is negative if so then b = rs +maxsum where b is the maxsum then ou initial claim that rs is part of the maxsum array is false so we drop it in simple word if rs+b is less than b then rs will always weigh us down so we drop it

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

    Best video on RUclips to explain kadane's algo

  • @rahuls331
    @rahuls331 5 лет назад +7

    At 1.26 you have said that kadane algo only works on positive array. For a positive array, entire array is a longest sum contigous block. Considering subarray can also be the whole array.

    • @techdose4u
      @techdose4u  5 лет назад +19

      I mean to say that kadane's algo works when atleast 1 number is positive (I presented it in an ambiguous way). If you have all negative numbers then kadane's was taking max_ending_here = 0 which would never get updated because all numbers are negative and output would be 0. I hope you get it now.

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

    Great logic, I'm currently using this to learn for my Microsoft Interview.
    Thanks alot man, practiced and memorized this algorithm. I'll try to do it daily.
    Cheers from Florida, keep up the videos. You got a sub my man.

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

    Thank you, for this nice and clean explanation

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

    Thanks sir :-)
    Simple code snippet for easy understanding : C++
    int maxSubArray(vector& nums) {

    int max_sum = INT_MIN, curr_sum = 0;
    for(auto num: nums){

    curr_sum += num;
    max_sum = max(curr_sum, max_sum);
    if(curr_sum < 0) curr_sum = 0;
    }

    return max_sum;
    }

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

    no one can explain it like u.. god bless u

  • @consistentthoughts826
    @consistentthoughts826 4 года назад +11

    For Python coders:
    def maxsubarray(arr):
    n = len(arr)
    curr = arr[0]
    final = arr[0]
    for i in range(1,len(arr)):
    curr = max(arr[i],curr+arr[i])
    final = max(curr,final)
    return final

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

    tum jo aaye zindagi mei baat bann gayi.awesome explanation

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

    You are GOD in explaining algorithms 🙂

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

    I have seen many videos,but this one solved my doubtssss🙏🙏🙏🙏🙏

  • @blindprogrammer
    @blindprogrammer 5 лет назад +3

    the best explanation so far found on any source!

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

    Perfect Solution I found.. Thank you so much 👍

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

    for better understanding read the conditions as : a[i] > meh & meh > msf

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

    Thanks for the video, I was trying to solve this problem for 1 day

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

    The best explanation out there

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

      Thanks

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

      @@techdose4u Kindly guide how to print the elements of the desired max subarray

  • @l.paulsonraja4036
    @l.paulsonraja4036 4 года назад +1

    Best Video for Kadanes algorithm.

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

    Good explanation. Got more clear to me.!

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

    mast video banai, bhaiya, sab samajh aa gya.

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

    Easy to understand.
    arr=list(map(int,input().split()))
    maxi=arr[0]
    sumi=0
    for i in arr:
    sumi+=i
    if sumi

  • @Dankman3
    @Dankman3 5 лет назад +2

    Clear and informative as usual. Good job.

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

    Very simple and it works THANK YOU

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

    Fantastic explanation !!
    Simple code snippet for easy understanding :
    private int solve(int[] arr){
    int prefixSum = 0;
    int max = Integer.MIN_VALUE;
    for (int elem : arr) {
    prefixSum += elem;
    prefixSum = Math.max(prefixSum, elem);
    max = Math.max(max, prefixSum);
    }
    return max;
    }

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

    I dont earn atm, but when i start earning, I'll make sure to support ur channel

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

      Thanks for your support :)

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

    This algo is awesome, the author is supper hero.

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

    Best explanation so far.

  • @KuchBhi24211
    @KuchBhi24211 6 месяцев назад

    we can use sliding window algo here to get the exact subarray as well

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

    Nice explanation with all possibilities

  • @Bunny-yy6fo
    @Bunny-yy6fo 3 года назад +3

    Your explanation is very good . But, one suggestion I want to give , i.e:- you are directly explaining the method it will be better if you explain from sratch like from where this method came and how to get this approach like that ...
    Thanks for great explanation

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

      Nobody will watch that as it will increase the length of video. Most people watch the videos when they are tight on schedule :)

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

      @@techdose4u I only watch your videos just because of the explanation part and thought process.

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

    In the brute force approach, you said it will be the order of O(n^2).
    pseudocode for the brute force approach :
    sum=0
    for (i=0 to n)
    for (j=i to n) //two loops for finding all substrings.
    max(sum,sum(i to j)) // sum of that substring.
    I think this brute force approach will take O(n^3) order.
    Correct me, if I am wrong :)

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

    Bro best one keep making videos ☺️

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

    Nice,
    But for kadanes algo there is condition of atleast one positive number must be present in array.
    So, this problem will solve easily by kadane algorithm.

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

    Best 😇😇😇 explanation

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

    Like these 27 people are even humans?
    This is the easiest approach I have ever seen for this algorithm and tech dose have explained it in the best way

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

      Thanks

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

      @@techdose4u Possibly your code doesn't work correctly for multiple test-cases (TCs).

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

    Man outstanding solution my brain cant even think of it

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

    excellent video Straight to the point thank you

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

    Amazing explanation !!!

  • @MohamedAshraf-ri9wb
    @MohamedAshraf-ri9wb 2 года назад

    how to track using left and right pointer to get that array

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

    Best Explanation!!

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

    very good explanation

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

    how can we keep trackof subarray indices side by side??? i mean how would iteration take place?

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

      If you find a max value then just save the ending index. After kadane's is done, just parse the array from the saved index in reverse order. Stop when sum value is same is maxSum. That index is your left index :) Congrats, you have now found the window.

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

    how did you get the intuition for that ?

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

    what if we had to return the maximum sub array? for that we will have to use n^2 approach right?

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

      No. You can maintain a left window pointer which will update whenever the current sum falls below 0

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

      @@techdose4u could you please elaborate it more in detail?

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

    @TECH DOSE can u tell why this problem is there in your DP Playlist? How is it related to DP

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

      It's a DP algo.

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

      @@techdose4u So a DP algo can be made without using extra space right??

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

    if (max_ending_here < 0)
    max_ending_here = 0;
    why this is also working

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

    thankuu it worked for -ve numbers alsoo

  • @dabybaly7246
    @dabybaly7246 3 месяца назад +1

    dude i dont have any basic ideas about c or c++ and i know python should i learn dp in pyhton or i should learn dp in c++ and learn along what these syntaxes are?

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

      I would recommend you to learn DP by implementing from scratch. The cache in python don't let you learn DP. But, you can skip that and implement all logic yourself and learn it in Python too :)

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

    Well described!! THANKYOU

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

    helped a lot to understand... Thanks sir

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

    Great content bro !!

  • @Relaxingmusic-tw4qn
    @Relaxingmusic-tw4qn 4 года назад +2

    bro if possible can u 1st make recursive version + memorization of kadance ,Longest common subsequence,and few more parent question its helps us to develop logic and how to use dp in these question.
    and btw ur explanation is super awesome and easy to grasp thanks brother :)

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

      On my way. Currently doing it.

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

    how to get the exact subarray if required?

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

    how do cal indices with same logic? please explain me a bit of it

  • @himanshugpt7
    @himanshugpt7 2 месяца назад

    One of the best explanations!! Great work @Techdose4u

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

    👌👍 excellent sir

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

    Bro this Playlist is enough for clearing MNC Coding interview pls reply.
    Very well explaination bro. I loved it.

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

      It's good but not enough. Try to cover as much as you can from all my playlists.

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

    great explanation sir!!

  • @PramodYadav-dr9vq
    @PramodYadav-dr9vq 4 года назад

    how did you decide the first element of subarray

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

    When should we update the pointers?

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

      You need to check when value falls below min.

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

    Sir, this logic is not working for [-2,3]

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

    There is one queston with respect to the above concept. For example if I have arr = [1, -2, 3], then manually i know that
    subrray with index 2 i.e [3] will hold the maximum sum. I am speaking with respect to contagious array. Subarray by taking the third element is also contagious according to me. If i run the above mentioned concept code, I get the result as 1, which means first element of the array but result from manual approach is not same.
    Can you please explain me where I am lacking or do i need better understanding of contagious array.

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

    can any one provide here this algorithm implementation in python....?

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

    How to use INT_MIN in Python 3

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

    i did not understand what is INT_MIN please reply me

  • @b.sainathreddy4567
    @b.sainathreddy4567 4 года назад +1

    can u explain how to find kth largest contiguous sub array instead of largest contiguous subarry using kadanes alogrithm

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

      Can you further explain the statement and give the problem link.

    • @b.sainathreddy4567
      @b.sainathreddy4567 4 года назад

      @@techdose4u www.geeksforgeeks.org/k-th-largest-sum-contiguous-subarray/
      this one :)

  • @saicharan-lj2bz
    @saicharan-lj2bz 4 года назад +1

    This Helped. Thank You.

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

    Nicely u explained

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

    You are a life saver. Any advice how do I implement primes into it? Also subbed

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

      Primes meaning ?

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

      @@techdose4u Number that can be divided only by themselves and 1, i.e 2, 3, 5, 7, 11 etc. I have to find largest subarray under the condition that absolute value of every number of it is prime number.

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

    Very well explained sir

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

    Great tutorial...Thank You

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

    Which software do you use

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

    What is the default value of int_min?

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

    Initially "msf" is 0(zero) you said. In the second if condition 0(zero) is not less than -2 know. Then second if statement also fails for the first loop. But you explained msf becomes -2 after 1st loop. How is it possible?

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

    Great work sir but what is the intuituion behind this algo?

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

    Hi can I know why you modified existing also what kind of issues are you trying to solve?

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

    can u explain why we check this condition if(meh

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

    Best Video 🤞🏻

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

    shouldnt msf be array[0]?

  • @NitishKumar-xr9tx
    @NitishKumar-xr9tx 4 года назад +1

    Nice explanation

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

    Sir which app you use for making these videos??

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

    How to print max sum contiguous sub-array?

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

      When you slide and update your max_so_far, just maintain two int variables which will store the index where you are updating your value. At the end of parse, your index values stored will give the window starting and ending index. I hope you got it :)

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

      @@techdose4u Thnx :)

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

    In python it is two lines
    meh = max(a[i], meh + a[i] )
    msf = max( meh, msf)

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

      you can do that in c++ too

  • @dkprajapatiofficial8357
    @dkprajapatiofficial8357 5 лет назад +3

    very good performance

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

    nice explanation

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

    Superb bro