Maximum Sum SubArray (Kadane's algorithm) (Largest Sum Contigous SubArray)

Sdílet
Vložit
  • čas přidán 21. 05. 2017
  • Find the subarray with the maximum sum in an array. The solution is given by the Kadane's algorithm. Also called Largest Sum Contigous SubArray.

Komentáře • 184

  • @tanmayagarwal8513
    @tanmayagarwal8513 Před 3 lety +17

    I love the way how innocently he teaches.

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

    Best Explanation of Kadane's Algo I have ever seen. The most important thing that you explained the algo into two parts -
    1. Find the greatest sum
    2. Find the starting and ending indices of subarray containing the max sum

  • @christmas_fox-marychristma2801

    Thank you so much for posting this videos! You have such clear explanations!

  • @armanmanukyan1970
    @armanmanukyan1970 Před 3 lety

    After wandering in a lot of youtube channels, eventually I've found the best explanation here. Thanks.

  • @mahesh_kndpl
    @mahesh_kndpl Před 4 lety

    The way you explain is so clear. Thanks man.

  • @DAVISBENNYMIS
    @DAVISBENNYMIS Před 5 lety +8

    (2 Line solution ) :-
    int Kadane(int[] arr){
    int localmax=arr[0];
    int globalmax=arr[0];
    for(int i=1;i

    • @ajayshukla7238
      @ajayshukla7238 Před 5 lety

      nice one

    • @premkumareaswaran6875
      @premkumareaswaran6875 Před 4 lety

      What's n here? If it is the length of the array, I get 22 for the above array that Vivekanand has used for the tutorial. Did you try using it before posting the 2-line answer?

    • @sandip_kanzariya8476
      @sandip_kanzariya8476 Před rokem +1

      Superb solution ☺️😃 enjoy 🤠
      Can you explain this solution ?

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

    Thank you for explaining the Maximum Sum Subarray algorithm in such an easy way. You are really good teacher! Keep up the good work!!!

  • @singarajusureshkumar2330

    one n only one best explaination of kadane's algo

  • @gautamtyagi8846
    @gautamtyagi8846 Před 3 lety

    brilliant explanation! the big thing is he makes it much easier to understand. thanks a lot.

  • @meherkhan933
    @meherkhan933 Před 6 lety +1

    You are great Sir! You make so simple with your extraordinary explanation! Thank you very much!!!

  • @SunilKumar18
    @SunilKumar18 Před 7 lety +9

    Great work man. Brilliant explanation. Please keep doing more videos. hope your channel grows.

  • @LarryRuane
    @LarryRuane Před 7 lety +1

    Great explanation, I love it. One small simplification may be that max_so_far can be initialized to zero, rather than a[0]. Another advantage of making that change is that if the array is zero-length (size==0) you won't be accessing invalid memory.

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

      you can handle an empty array with a base case that checks for an empty array and simply returns (i.e. if (arr.length === 0) return). If you initialize max_so_far to 0, a test case of [-2] (or any negative number) will fail. I used [-2] as an example because that's the test case I failed on Leetcode lol

  • @sanketkumar1576
    @sanketkumar1576 Před 7 lety

    best explanation among all videos on this topic on youtube. thank you !

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

    Best explanation that i have seen for this algo

  • @SmartProgramming
    @SmartProgramming Před 5 lety

    awesome explanation sir, very very helpful, thanks a lot for this tutorial 👍👍👍👍🙂🙂🙂🙂

  • @jitendarsahani11
    @jitendarsahani11 Před 4 lety

    Bahut dino se struggle kr rha tha...lekin aaj samaj mei aa gaya. Thanx...

  • @swapnil814
    @swapnil814 Před 5 lety

    Thank you. You made tough problem, easy. :)

  • @princekumarmaurya1763
    @princekumarmaurya1763 Před 3 lety

    Best vedio I have ever seen for this solution 👍👍👍👍👍👍

  • @anindita2816
    @anindita2816 Před 5 lety

    Very good explanation. You're that favorite teacher kind of person! :)

  • @naveensharma5060
    @naveensharma5060 Před 7 lety

    finally i got the video by which i have understood this concept very easily.

  • @Piggybacking
    @Piggybacking Před rokem

    Thank you so much ! your explanation is so helpful.

  • @vaishnavia.n.312
    @vaishnavia.n.312 Před 3 lety

    the way u explain is crystal clear, thank nu so much @vivek.

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

    You made things understand easier

  • @somesbhowmick2082
    @somesbhowmick2082 Před 5 lety

    Great , Great simply you explain I understand, keep doing it , I want learn more algorithm topic probmel

  • @PramodKumar-rc9zy
    @PramodKumar-rc9zy Před 6 lety

    Nice explain sir before watching this video i was confused that what the meaning of this algo but now cleared thanks a lot sir

  • @edwardcerverizzo7363
    @edwardcerverizzo7363 Před 5 lety +1

    I've seen this problem posted as a dynamic programming problem on Leetcode. I like this way better though. Is there any argument to do DP over this way?

  • @beholdpain
    @beholdpain Před 5 lety

    Nice, Very Detailed!

  • @Mohitsingh-mk8vr
    @Mohitsingh-mk8vr Před rokem

    best explanation of kadane algo

  • @shivam_0002
    @shivam_0002 Před 5 lety

    Great Explanation, make some more videos. Thanks

  • @nikhilbhatt9823
    @nikhilbhatt9823 Před 5 lety

    I think for efficient subarray it should be **if(max_ending_here

  • @karthikd7460
    @karthikd7460 Před 4 lety

    After seeing this video, I feel your one of the LC problems god!!!

  • @DhananjayTyagi24
    @DhananjayTyagi24 Před 5 lety

    Explained well!

  • @rushi901
    @rushi901 Před 6 lety +1

    Any idea about how to convert the finding the start index and end index into 2 D array ?

  • @mohit0001ish
    @mohit0001ish Před 6 lety

    Very Well Explained :)

  • @anshubansal2008
    @anshubansal2008 Před 6 lety

    Great Explanation.

  • @prakashkumaran9767
    @prakashkumaran9767 Před 5 lety

    Good work. Easy to learn. Thank you..

  • @josephmorales652
    @josephmorales652 Před 6 lety

    Thanks man!

  • @sailkargutkar1980
    @sailkargutkar1980 Před 5 lety

    Best way to explain max sub array prob thanks

  • @rahul-patil
    @rahul-patil Před 5 lety +3

    The second if condition is the core of this algo.

  • @chetanshrivastava3762
    @chetanshrivastava3762 Před 4 lety

    Nice explanation sir...You have great patience which is must for a programmer.
    Regarding this example,we can take a lesser size array to save time.

  • @AbhishekJain-pm2jn
    @AbhishekJain-pm2jn Před 2 lety +1

    Thank you sir for explaining in such a easy way 🙏

  • @tapanjeetroy8266
    @tapanjeetroy8266 Před 5 lety

    Thanks a lot lot sir..you explain us so well

  • @Ankit13555
    @Ankit13555 Před 7 lety

    you are simple and great....plzz provide some good and tuff DP problems ...:)

  • @harshtulsyan9894
    @harshtulsyan9894 Před 7 lety

    Nice Explanation sir...
    Please upload more videos on Dynamic Programming..!!

  • @mordiabukarat3985
    @mordiabukarat3985 Před 5 lety

    very helpful , thank you

  • @Dragondavid
    @Dragondavid Před 6 lety +17

    What if all elements are negative value? How do you dandle max_ending_here < 0 ? How would you track indices?

    • @komuravellyvenky
      @komuravellyvenky Před 5 lety +6

      Above algorithm will not work if all the elements are negative. Please refer : www.techiedelight.com/maximum-subarray-problem-kadanes-algorithm/

    • @tejeswarsahu2498
      @tejeswarsahu2498 Před 5 lety

      This info is very helpful...

    • @edwardcerverizzo7363
      @edwardcerverizzo7363 Před 5 lety

      Solution is trivial. Return an empty array. Sum of all elements is zero (since there are no elements). 0 is strictly greater than any combination of negative numbers. You could create a subroutine to scan the array and return this result if this is the case. Total running time should be O(2n) which is still O(n).

    • @jogeswararaonynala1591
      @jogeswararaonynala1591 Před 4 lety

      Then just take the element with with highest value in all negative numbers

    • @sharidass1408
      @sharidass1408 Před 4 lety

      @@komuravellyvenky this code also fails if array is [-1]

  • @rajatmishra3572
    @rajatmishra3572 Před 4 lety

    nice explanation!!

  • @saurabhsharma8577
    @saurabhsharma8577 Před 6 lety

    Nice Work, Thank you Sir

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

    thank you

  • @ghughal
    @ghughal Před 5 lety

    Will this algorithm work for an input array {5, -2, -1, 3, -4}. Just a second set of eyes to verify we get the result as maximum length of the subarray is 4. Please help!

  • @TanujMishra077
    @TanujMishra077 Před 6 lety

    Great work Sir. Nice explanation.

  • @dorararo
    @dorararo Před 3 lety

    can we print the largest sub-array that was found , using Kadane algo?..we can get the end point of that sub-array but how do we get its starting point.

  • @shimpyasthana5561
    @shimpyasthana5561 Před 5 lety

    Great work

  • @shobhitmittal77
    @shobhitmittal77 Před 7 lety +2

    Hi Vivekanan sirji, you are doing a great job..
    I have watched some of your other videos too and must say they are simply awesome and to the point..
    It will be even better if you could organize your uploaded videos into a playlist, it will direct the users to your other videos.... just a suggestion :)

    • @srinidhiii
      @srinidhiii Před 7 lety

      well said.it ll be great if a playlist is created topicwise.Your tutorial is awesome sir

    • @vivekanandkhyade
      @vivekanandkhyade  Před 7 lety

      Yes shobhit i will make it...! Thanks ....!

    • @vivekanandkhyade
      @vivekanandkhyade  Před 7 lety

      Yes srinidhi ...will make it..!

  • @mani8110
    @mani8110 Před 10 měsíci

    thank you best explanation❤❤

  • @ravikishoretottaramudi1263

    Very good explanation sir

  • @aryangarg9072
    @aryangarg9072 Před 3 lety

    Good explanation

  • @sagarsalunkhe6429
    @sagarsalunkhe6429 Před 7 lety

    Thanks for explanation
    very well done

  • @niharikaepuri3305
    @niharikaepuri3305 Před 6 lety

    Can you please make a video on Largest subarray with equal number of 0s and 1s with O(N) time complexity and also please make a video on Maximum Product Subarray?

  • @dharnisingh11
    @dharnisingh11 Před 4 lety

    What if we do not have any negative number present in the array?

  • @LarryRuane
    @LarryRuane Před 7 lety

    One more observation ... What if the array consists entirely of negative values? This algorithm will report start and end both zero, which is a subarray of length 1. It seems like it may be better, in general, for the result to be reported as a start index and a length (rather than end index). Then the correct answer in this case (all elements negative) is start = zero (or really anything), length = zero. I implemented this here: codepad.org/irM2hs1b

  • @baibhavghimire3827
    @baibhavghimire3827 Před 6 lety

    Nice one..Yes need to do like 1.5x or 2x..lol...But great presentation!!

  • @tirnasircar2938
    @tirnasircar2938 Před 3 lety

    What will happen if there are no negative numbers in the array?

  • @manojbgm
    @manojbgm Před 7 lety +1

    Nice Video. Well structured. Liked the way you simplified the solution in 2 parts.
    1) find the max sum
    2) look for index
    Nice work thank you.....

  • @prudhviprasad6386
    @prudhviprasad6386 Před 3 lety

    Thnks sir it was very detailed explanation

  • @ASHISHSINGH-nj6es
    @ASHISHSINGH-nj6es Před 5 lety +6

    Algorithm tracing != Explaining

  • @ShivangiSingh-wc3gk
    @ShivangiSingh-wc3gk Před 6 lety

    Thank You

  • @prateekkanujiya9775
    @prateekkanujiya9775 Před 5 lety

    Awesome 👍

  • @ayonkar1534
    @ayonkar1534 Před 6 lety

    What if all the elements in the array is set to 0?

  • @shankysays
    @shankysays Před 3 lety

    If my array is -5 -4 -3-1 -2 will this algo work?

  • @Dyslexic_Neuron
    @Dyslexic_Neuron Před 5 lety +1

    your understanding of the problem is Bad.....
    The way I see the problem is 3 cases : Life Hope and Death.
    We'll take 2 sum variables' : prev_sum and current_sum.
    Life is when we encounter only positive number: we will update prev_sum in this case
    Hope is when we encountered a negative number but that negative number has not made my current sum less than zero so there is still hope that some next number may repair the damage done by the negative number. : we will update prev_sum when current_sum > prev_sum
    Death is when the current sum becomes negative .....so now in this case we have re-initialize the starting point for calculating current sum
    Below is my smart : : code
    public static int findLargestSum(int a[]) {
    int end = 0;
    int current_sum = 0;
    int prev_sum = 0;
    while (end < a.length) {
    current_sum += a[end];
    if (current_sum < 0) { // death case
    current_sum = 0;
    }
    if (current_sum > prev_sum) {
    prev_sum = current_sum;
    }
    end++;
    }
    return prev_sum;

  • @Bakepichai
    @Bakepichai Před 6 lety

    Keep it up

  • @argharoy6571
    @argharoy6571 Před 4 lety

    Sir you are awesome

  • @yunuskocatas3879
    @yunuskocatas3879 Před 2 lety

    why we equalise the max ending here to zero on second if

  • @MyLifeMyWorld08
    @MyLifeMyWorld08 Před 6 lety +1

    Hello Sir,
    Can you please post video for solution of "maximum/minimum element from each sub-array of size 'k'" in O(n) ?
    Thanks in advance.

  • @YogeshKumar-ye8nd
    @YogeshKumar-ye8nd Před 6 lety

    if I will take only all elements negative except first then this code will not give the index of maximum subarray you can check it

  • @alokkumarsingh4118
    @alokkumarsingh4118 Před 3 lety

    Sir will the algorithm work if the maximum sum is negative?

  • @muhammahanisuzzaman5493

    Carry On...

  • @Muthuvlog104
    @Muthuvlog104 Před 2 lety

    Good explanatiin

  • @DurgaShiva7574
    @DurgaShiva7574 Před 3 lety

    will this algo works if we have the max sum in -ve itself....i.e if all the elements of the array are -ve, then what to do ?

  • @Sudhanshusable98
    @Sudhanshusable98 Před 4 lety

    Thank you sir 🙏

  • @jakusam4564
    @jakusam4564 Před 6 lety

    sir thank you very much.i am from bangladesh.

  • @srinidhiii
    @srinidhiii Před 7 lety

    awesome

  • @yunuskocatas3879
    @yunuskocatas3879 Před 2 lety

    perfect explenentation

  • @modernsanskari4398
    @modernsanskari4398 Před 7 lety +2

    grt sir .But this question was asked in my interview but i was not aware of this algo.But i gave a brute force solution by using two loops O(n^2).Here in this algo it is taking linear time o(n). Can we make it to O(log n) by using divide and conquer approach?

    • @santhoshcts5
      @santhoshcts5 Před 7 lety +5

      if the array is not sorted , we cannot do it in o(logn) . in other way , meaning only binary search will make time complexity of o(logn) and binary search will work only on sorted arrays .

    • @Alexc99xd
      @Alexc99xd Před 5 lety

      You could divide and conquer in O(nlog(n)) recursively Find max on left, max on right, and find max that crosses the midpoint

  • @shivamvyas8899
    @shivamvyas8899 Před 3 lety

    Hello sir, can u make a video on Z algorithm for String search.

  • @karanshah9310
    @karanshah9310 Před 4 lety

    Longest Palindrome in a string

  • @binhbeng2701
    @binhbeng2701 Před 5 lety

    thanks!!!!!!!!

  • @mahal9647
    @mahal9647 Před 5 lety

    Thanks Vivek

  • @mohamedanwar6073
    @mohamedanwar6073 Před 7 lety

    please do video , print all different simple cycle in undirected graph . 🙌

  • @abhishekbisherwal6856
    @abhishekbisherwal6856 Před 5 lety

    NO need to check whether the sum is less than zero or not else do check whether calculated sum is greater than added element or not ? and rest will be same .

  • @hemanth8444
    @hemanth8444 Před 3 lety

    Sir plz explain dijkstras algorithm with snippet like this sir

  • @nupurchoudhary5707
    @nupurchoudhary5707 Před 6 lety

    thanks

  • @adithyareddy7611
    @adithyareddy7611 Před 7 lety

    HI Sir, Can you upload Matrix related java programs with algorithm explanation ... Please sir

  • @arbindsharma1423
    @arbindsharma1423 Před 3 lety

    sir how to approach the algo please teach that not as ratta mar study

  • @brijbhushanawasthi7679
    @brijbhushanawasthi7679 Před 6 lety +54

    Set the speed to 1.5, Thank me later:)

  • @sivas8620
    @sivas8620 Před 7 lety

    Please do a video Tutorial on Flatten a Linkedlist, Union of 2 Linkedlist

  • @MrVazanth
    @MrVazanth Před 7 lety

    Hi Vivekanand,
    Please help me with video to print given matrix in diagonal order
    Thanks

  • @rajporu9
    @rajporu9 Před 7 lety

    Vivek, the way you explain is crystal clear by giving examples. Keep up the good work. God Bless.

  • @gaymonkey5270
    @gaymonkey5270 Před 6 lety +4

    What if all values are negative?????

    • @compeng2013
      @compeng2013 Před 6 lety +4

      it will return the greatest negative number. So if you have an array = [-6, -5, -20, -1], it will return -1

    • @sauravbhagat4737
      @sauravbhagat4737 Před 5 lety +3

      @@compeng2013 No it is going to return 0, we need to modify the code little bit

    • @jogeswararaonynala1591
      @jogeswararaonynala1591 Před 4 lety

      Just take the highest elment in the negative no