Kadanes algorithm | Longest sum contiguous subarray

Sdílet
Vložit
  • čas přidán 21. 06. 2019
  • This video explains the modified version of kadane's algorithm that works for both positive as well as negative values in an array. This algorithm is used to find the largest sum contiguous subarray from a given array. Kadanes algorithm is one of the most common question in programming interviews. If you find any difficulty or have any query then do COMMENT below. PLEASE help our channel by SUBSCRIBING and LIKE our video if you found it helpful...CYA :)

Komentáře • 263

  • @debangan
    @debangan Před 3 lety +69

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

  • @YisName
    @YisName Před 4 lety +84

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

    • @techdose4u
      @techdose4u  Před 4 lety

      Thanks :)

    • @RudraSingh-pb5ls
      @RudraSingh-pb5ls Před 4 lety +6

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

    • @RudraSingh-pb5ls
      @RudraSingh-pb5ls Před 4 lety +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 Před 3 lety +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 Před 3 lety +4

      @@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 !

  • @alexpadilla5741
    @alexpadilla5741 Před 3 lety +61

    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 Před 16 dny

    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.

  • @subham5785
    @subham5785 Před 3 lety +2

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

  • @Usurperhk
    @Usurperhk Před 3 lety +7

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

  • @rohiteshkumarjain7772
    @rohiteshkumarjain7772 Před 4 lety +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  Před 4 lety +67

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

    • @AdityaRaj-bn3ht
      @AdityaRaj-bn3ht Před 3 lety +3

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

    • @nishant5249
      @nishant5249 Před 3 lety +3

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

    • @binod3204
      @binod3204 Před 3 lety +4

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

    • @techdose4u
      @techdose4u  Před 3 lety +7

      Stay connected with us ☺️

  • @expansivegymnast1020
    @expansivegymnast1020 Před rokem

    Very simple and it works THANK YOU

  • @alishasingh4382
    @alishasingh4382 Před 2 lety +1

    Thank you, for this nice and clean explanation

  • @sarfarazhussain6883
    @sarfarazhussain6883 Před 3 lety +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 Před 2 lety

      MSF - Max So Far
      MEH - Max Ending Here

    • @sarfarazhussain6883
      @sarfarazhussain6883 Před 2 lety

      @@vitaliitomas4057 I know that.

    • @hodgsontetteh4058
      @hodgsontetteh4058 Před 2 lety +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

  • @rahuls331
    @rahuls331 Před 4 lety +8

    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  Před 4 lety +20

      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.

  • @Dankman3
    @Dankman3 Před 5 lety +2

    Clear and informative as usual. Good job.

  • @rushikeshborse1994
    @rushikeshborse1994 Před 3 lety +4

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

  • @gundasreedhar327
    @gundasreedhar327 Před 2 lety

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

  • @rajendransubramanian6813

    Thanks for the good explanation, but how did you select the contiguous elements from 4 to 5, i mean the index starts from 2 to 6

  • @ganesh_130
    @ganesh_130 Před 3 lety +3

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

  • @ajaywadhwa3398
    @ajaywadhwa3398 Před 3 lety +1

    how did you get the intuition for that ?

  • @salonimaniyar3943
    @salonimaniyar3943 Před měsícem

    Perfect Solution I found.. Thank you so much 👍

  • @sunilpatel6542
    @sunilpatel6542 Před 4 lety

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

  • @consistentthoughts826
    @consistentthoughts826 Před 3 lety +10

    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

  • @ashwinraj8918
    @ashwinraj8918 Před 4 lety +2

    The best explanation of Kadanes Algo!!

  • @PramodYadav-dr9vq
    @PramodYadav-dr9vq Před 3 lety +1

    how did you decide the first element of subarray

  • @ambrish8144
    @ambrish8144 Před 4 lety +1

    excellent video Straight to the point thank you

  • @adhaarsharma753
    @adhaarsharma753 Před 3 lety +2

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

  • @MohamedAshraf-ri9wb
    @MohamedAshraf-ri9wb Před rokem

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

  • @adityarathi3420
    @adityarathi3420 Před 3 lety +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;
    }

  • @s50498
    @s50498 Před 3 lety

    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.

  • @newgamer4669
    @newgamer4669 Před 7 měsíci

    Well described!! THANKYOU

  • @tekno864
    @tekno864 Před 2 lety

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

  • @killeraloo3247
    @killeraloo3247 Před 2 lety

    mast video banai, bhaiya, sab samajh aa gya.

  • @hanumanthram6754
    @hanumanthram6754 Před 11 měsíci

    Good explanation. Got more clear to me.!

  • @tuhinkumardolai9836
    @tuhinkumardolai9836 Před 3 lety

    helped a lot to understand... Thanks sir

  • @saicharan-lj2bz
    @saicharan-lj2bz Před 3 lety +1

    This Helped. Thank You.

  • @MadForCs16
    @MadForCs16 Před 4 lety +1

    Best explanation so far.

  • @Shashank0002
    @Shashank0002 Před 3 lety

    Sir which app you use for making these videos??

  • @ashutoshsinghpatel196

    You are GOD in explaining algorithms 🙂

  • @adnanjmi21
    @adnanjmi21 Před 4 lety

    Useful tutorials , which sw/tool use for writing this

  • @arjunkhanna1803
    @arjunkhanna1803 Před 4 lety +3

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

  • @riteeshbommaraju
    @riteeshbommaraju Před 3 lety +6

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

  • @shaswatsingh
    @shaswatsingh Před 4 lety

    Which software do you use

  • @shubhamjaiswal9314
    @shubhamjaiswal9314 Před 3 lety +1

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

  • @sehejwahla5437
    @sehejwahla5437 Před 3 lety +1

    Great content bro !!

  • @theyoutubespecialist9004
    @theyoutubespecialist9004 Před 2 lety +17

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

  • @jayantakumarroy543
    @jayantakumarroy543 Před 4 lety +2

    tum jo aaye zindagi mei baat bann gayi.awesome explanation

  • @patilsoham
    @patilsoham Před 4 lety +1

    Great tutorial...Thank You

  • @activecoder1844
    @activecoder1844 Před 3 lety

    What is the default value of int_min?

  • @suman6327
    @suman6327 Před 4 lety +4

    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;
    }

  • @nagavarma7006
    @nagavarma7006 Před 4 lety +1

    Man outstanding solution my brain cant even think of it

  • @koyavasudhalakshmi2073
    @koyavasudhalakshmi2073 Před 3 lety +2

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

  • @harshit4190
    @harshit4190 Před 4 lety +1

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

  • @Relaxingmusic-tw4qn
    @Relaxingmusic-tw4qn Před 3 lety +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 :)

  • @l.paulsonraja4036
    @l.paulsonraja4036 Před 3 lety +1

    Best Video for Kadanes algorithm.

  • @rishurana9655
    @rishurana9655 Před 3 lety

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

  • @kshitijgaur9635
    @kshitijgaur9635 Před 3 lety +1

    Amazing explanation !!!

  • @porassingh4904
    @porassingh4904 Před 2 lety +1

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

    • @techdose4u
      @techdose4u  Před 2 lety +1

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

    • @osamaraza6001
      @osamaraza6001 Před 2 lety

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

  • @tungtruong5904
    @tungtruong5904 Před 3 lety +1

    This algo is awesome, the author is supper hero.

  • @nishalgoud2286
    @nishalgoud2286 Před 4 lety

    How to keep track of position of contiguous subarray using pointers?

  • @Vsumit17OG
    @Vsumit17OG Před 3 lety +3

    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.

  • @neojai3514
    @neojai3514 Před 16 dny

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

  • @jordanguada4354
    @jordanguada4354 Před 3 lety +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.

  • @shouryatrivedi2172
    @shouryatrivedi2172 Před 3 lety +1

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

    • @techdose4u
      @techdose4u  Před 3 lety

      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.

  • @vedantmondkar9963
    @vedantmondkar9963 Před 3 lety +1

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

  • @atharvprasadparanjape6140

    How to use INT_MIN in Python 3

  • @BurhanAijaz
    @BurhanAijaz Před rokem

    how to get the exact subarray if required?

  • @agileprogramming7463
    @agileprogramming7463 Před 4 lety +1

    So neat!!

  • @sehejwahla5437
    @sehejwahla5437 Před 3 lety +4

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

  • @sakshirana1912
    @sakshirana1912 Před 2 lety

    can u explain why we check this condition if(meh

  • @blindprogrammer
    @blindprogrammer Před 4 lety +3

    the best explanation so far found on any source!

  • @prajwalsrivastava1983
    @prajwalsrivastava1983 Před 4 lety

    Very well explained sir

  • @prateekaryan1020
    @prateekaryan1020 Před 4 lety +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 :)

  • @spoiler407
    @spoiler407 Před 2 lety +1

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

  • @Salmanul_
    @Salmanul_ Před 3 lety

    Thanks!

  • @MunniDivya
    @MunniDivya Před 3 lety +2

    thankuu it worked for -ve numbers alsoo

  • @gurnoorsingh2954
    @gurnoorsingh2954 Před 4 lety +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  Před 4 lety

      Thanks

    • @harshmanola563
      @harshmanola563 Před 3 lety +1

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

  • @coder2684
    @coder2684 Před 3 lety

    Nicely u explained

  • @rishiAura
    @rishiAura Před 2 lety +1

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

  • @naturelover5824
    @naturelover5824 Před 4 lety

    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?

  • @jjbrotherscreation3267
    @jjbrotherscreation3267 Před 4 lety +2

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

    • @techdose4u
      @techdose4u  Před 4 lety +2

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

  • @ashwikraoalladi3320
    @ashwikraoalladi3320 Před rokem

    👌👍 excellent sir

  • @nutankumari9977
    @nutankumari9977 Před 2 lety +1

    Nice explanation with all possibilities

  • @shrutigupta9319
    @shrutigupta9319 Před 3 lety +1

    Best Explanation!!

  • @santasingh9045
    @santasingh9045 Před 3 lety +1

    great explanation sir!!

  • @ThanosAtWork
    @ThanosAtWork Před 3 lety +1

    Bro best one keep making videos ☺️

  • @vishwanathhosmane3834
    @vishwanathhosmane3834 Před 2 lety

    Sir from which place you belongs to? Plz reply

  • @saisanthosh8370
    @saisanthosh8370 Před 3 lety

    how to use int_main in python

  • @palakurthybadrieshwar9999

    i did not understand what is INT_MIN please reply me

  • @vitaliitomas4057
    @vitaliitomas4057 Před 2 lety +1

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

    • @techdose4u
      @techdose4u  Před 2 lety

      Primes meaning ?

    • @vitaliitomas4057
      @vitaliitomas4057 Před 2 lety

      @@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.

  • @namanvohra8262
    @namanvohra8262 Před 2 lety +1

    The best explanation out there

    • @techdose4u
      @techdose4u  Před 2 lety

      Thanks

    • @osamaraza6001
      @osamaraza6001 Před 2 lety

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

  • @himanshudhyani6076
    @himanshudhyani6076 Před 4 lety +2

    How to print max sum contiguous sub-array?

    • @techdose4u
      @techdose4u  Před 4 lety +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 Před 4 lety

      @@techdose4u Thnx :)

  • @b.sainathreddy4567
    @b.sainathreddy4567 Před 3 lety +1

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

    • @techdose4u
      @techdose4u  Před 3 lety

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

    • @b.sainathreddy4567
      @b.sainathreddy4567 Před 3 lety

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

  • @subratamondal7056
    @subratamondal7056 Před 3 lety +1

    When should we update the pointers?

    • @techdose4u
      @techdose4u  Před 3 lety

      You need to check when value falls below min.

  • @villagevlogger4615
    @villagevlogger4615 Před rokem

    Easy Explanation

  • @myriad1703
    @myriad1703 Před rokem

    nice explanation

  • @mukulkirtiverma2781
    @mukulkirtiverma2781 Před 3 lety +1

    Super video! I applauded for ₹40.00 👏

  • @sidkapoor9085
    @sidkapoor9085 Před 2 lety

    shouldnt msf be array[0]?

  • @anupamajayakanthan4402
    @anupamajayakanthan4402 Před 4 lety +1

    Hi Bro its an amazing explanation..... Can u also explain the same in case of a circular array

  • @azizulhakimsaif1420
    @azizulhakimsaif1420 Před 7 měsíci

    amazing

  • @nmkyuppie
    @nmkyuppie Před 3 lety +1

    Thanks man 😎

  • @osamaraza6001
    @osamaraza6001 Před 2 lety +1

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

    • @techdose4u
      @techdose4u  Před 2 lety

      Just track the starting index and window size. That's it

  • @jasmeenkaur6001
    @jasmeenkaur6001 Před 3 lety +2

    Best 😇😇😇 explanation