Maximum Subarray Sum | Leetcode | Kadane's Algorithm | Brute-Better-Optimal | CPP/Java

Поділитися
Вставка
  • Опубліковано 2 лис 2024

КОМЕНТАРІ • 582

  • @takeUforward
    @takeUforward  4 роки тому +103

    Please watch the new video which covers it in more depth, and also prints it: ua-cam.com/video/AHZpyENo7k4/v-deo.html
    .
    People thinking this does not works for negative numbers, have a closer look what maxi is initially initialised to.
    .
    If you appreciate the channel's work, you can join the family: ua-cam.com/channels/JskGeByzRRSvmOyZOz61ig.htmljoin

    • @piyushkhurana.7926
      @piyushkhurana.7926 4 роки тому +2

      Hello Bhaiya .
      Whenever I am trying to solve a question on codechef or geeksforgeeks , I am unable to solve the question , I did a lot of practice , I did understood the code and also I am choosing the right algo , but unable to solve . Can you please help ? I am using Java .

    • @deveshvishwakarma23
      @deveshvishwakarma23 4 роки тому

      Understood bro! 💯

    • @ak332
      @ak332 4 роки тому

      Hey striver
      Does anyone knows about Exposys Data labs internship
      Is it recommended to take it?
      They are asking for a registration fees.

    • @oshorajneesh7925
      @oshorajneesh7925 4 роки тому

      Understood🔥

    • @parthsachan3140
      @parthsachan3140 4 роки тому +11

      What if all the integers are negative??

  • @sasmalpayal
    @sasmalpayal 2 роки тому +63

    I haven't seen people explaining any problem in the brute force approach as well as in an optimal solution. Thank you so much for your good work.

  • @tanyacharanpahadi158
    @tanyacharanpahadi158 4 роки тому +198

    since the last four days. your videos are the first thing i watch in the morning. Great job brother.

    • @takeUforward
      @takeUforward  4 роки тому +25

      Awesome! Thank you!

    • @ritiksolanki6267
      @ritiksolanki6267 4 роки тому +4

      Same here😀.....your explanation is amazing 👍👍

    • @anonking6803
      @anonking6803 3 роки тому +4

      @@ritiksolanki6267 Congratulations Ritik for Nagarro!!😇 Whole Acropolis is proud of you!🙌🙌

    • @coffeebeans9238
      @coffeebeans9238 3 роки тому +1

      @@ritiksolanki6267 I have got multiple offers from TCS, Infosys, Wipro, Cognizant, Accenture. Without your guidance and motivation Ritik Sir. I am not able to get all this offers. Whole Acropolis is proud of you for having such a coder like you.
      #proud_acropolian

    • @PIYUSH-lz1zq
      @PIYUSH-lz1zq 3 роки тому

      @@coffeebeans9238 bro , how much you completed this sde sheet ??

  • @sourin.majumdar
    @sourin.majumdar 2 роки тому +31

    Never did Kadane's algorithm before but the way you explained, I wrote the correct code all by myself directly at one go!

  • @Ramya0216
    @Ramya0216 10 місяців тому +17

    2 yrs before i just reject his vedios because of some careless mistake of mine.i didn't have patience in that time. I was join for classes for DSA. but no uses. Now im here again for day and night with dsa vedios from striver channel.
    Thank you man😇❤

    • @nova9157
      @nova9157 4 місяці тому +1

      only if striver also made videos on spoken english

    • @TasneemMohammad-oj3ie
      @TasneemMohammad-oj3ie Місяць тому

      @@nova9157 lolllllllllll

  • @shobitjain9619
    @shobitjain9619 2 роки тому +46

    In the O(N^2) approach, j has to be initialized with i, not 0 at the beginning of the loop.

    • @aayushranjan5572
      @aayushranjan5572 Рік тому

      but why pls explain

    • @RituSharma-zp7xs
      @RituSharma-zp7xs Рік тому +3

      @@aayushranjan5572 O(n^2) approach will also work :
      class Solution {
      public int maxSubArray(int[] nums) {
      int max = nums[0];
      if (nums.length == 1) {
      max = nums[0];
      }
      for (int i = 0; i

    • @its_neel_ok
      @its_neel_ok Рік тому +1

      @@aayushranjan5572 initiallizing j with 0 doesn't make any sense since for n times (for i 0 to n-1)we will travelling the whole arrya(j= 0 to n-1)

    • @haripriyakulkarni3404
      @haripriyakulkarni3404 Рік тому

      @@RituSharma-zp7xs how will this cover all the subarrays?

    • @RituSharma-zp7xs
      @RituSharma-zp7xs Рік тому

      ​@@haripriyakulkarni3404
      With i = 0, j will go from 0 to len
      With i = 1, j will go from 1 to len
      With i = 2, j will go from 2 to len
      ..
      With i = len - 1, j will capture len - 1
      so, it taking sum of all subarrays and if it finds out max in between it will update. If you give me a test case where it will not work that would be great to understand where it is failing.

  • @RajanayakiScse
    @RajanayakiScse 4 роки тому +11

    Never seen a great video explaining this algorithm , this much simple :) Thanks a ton , bhaiya. Alllllll the kudos to you :)

    • @imshivendra
      @imshivendra 2 роки тому

      Bhaiya what is written inside for loop(auto:it) I'm unable to understand

  • @AyushKumar-tp4fb
    @AyushKumar-tp4fb Рік тому +7

    A big help for all the students as well as dsa learners . Thank you bro

  • @itzmartin20
    @itzmartin20 Рік тому +4

    Kudos for your dedication and crisp explaination!

  • @ddarrsh
    @ddarrsh Рік тому +1

    this is the only video on web, that clearly clearly explains the O(N) Solution to this problem , thank you!

  • @siddhanth3044
    @siddhanth3044 3 роки тому +5

    For those asking about what if all negative numbers were in array, it'll still work:
    Assume [-2, -1]
    First pass: maxi set to -2
    Sum = 0 + -2 = -2
    Is Sum > maxi? No, so no update
    Is Sum < 0? Yes, so no point carrying forward that sum, we just make it 0, so sum = 0
    Second pass: maxi is currently -2
    Sum = 0 + -1 = -1
    Is Sum > maxi? Yes, update maxi = sum = -1
    Is Sum < 0? Yes, so no point carrying forward this, update sum to 0
    End, maxi = -1

    • @imshivendra
      @imshivendra 2 роки тому

      Bhaiya what is written inside for loop(auto:it) I'm unable to understand

    • @nicoledsouza7761
      @nicoledsouza7761 2 роки тому

      what about [-2,1] please explain that as well

  • @yashnarkhedkar3734
    @yashnarkhedkar3734 2 роки тому +2

    📍To return subarray as well alongside maximum sum of subarray using kadane's algorithm
    👇👇👇👇👇👇
    void maxSubArray(vector&nums, int n){
    int maxi = 0, current_max = 0, start_index = 0, end_index = 0, j = 0;
    for(int i=0;i maxi){
    maxi = current_max;
    start_index = j;
    end_index = i;
    }
    if (current_max < 0){
    current_max = 0;
    j = i + 1;
    }
    }
    }

  • @nizarahamed.m1004
    @nizarahamed.m1004 Рік тому +1

    Brute force will only run 2 loops:
    public int maxSubArray(int[] nums) {
    int max = nums[0];
    int sum = 0;
    for(int i=0;i

  • @chaitanyamalegaonkar826
    @chaitanyamalegaonkar826 2 роки тому +8

    I think 'j' should start with 'i' instead of 0 for the bruteforce....the above bruteforce won't give the right answer if all the array elements are negative for ex.[-1,-2].but great video man!!

  • @MrChetan54
    @MrChetan54 2 роки тому +2

    I like the way you take us from brute force to optimal step wise

  • @om_1_2
    @om_1_2 4 роки тому +4

    Great bro. Liked it.
    I am a professional with 2 yrs of experience, and waiting for the new job from 5 months, and I am trying to prepare for faang, so that I can give intervoews next year. I am following this videos along with your faang video.
    And the main thing that I like is, not everyone can give all the time due to all personal work, everyone doesn't have same life, some have to do home stuff and all, but you taking out your time for these videos. Great bro. I can't give 4 hrs a day also for ds but hope some product based company recruit me someday.
    Thanks broooo for all your hard work.

  • @ShivamSingh-rj5jd
    @ShivamSingh-rj5jd 3 роки тому +2

    THIS IS THE BEST EXPLANATION OF KADANE'S ALGORITHM, CHANGE MY MIND ;-)). Great job brother!

  • @aadeshsharma0001
    @aadeshsharma0001 4 роки тому +51

    ye bnda ninjas blocks gfg ka dhndha bnd krwadega , thnx bro for these helping videos

  • @navyasri5077
    @navyasri5077 3 роки тому

    he is the only one helps me a lot ,i got so addicted to his vedio i am only doing problems he gave explanation .

  • @shubhamagarwal1434
    @shubhamagarwal1434 3 місяці тому

    #Free Education For All.. # Bhishma Pitamah of DSA...You could have earned in lacs by putting it as paid couses on udamey or any other elaerning portals, but you decided to make it free...it requires a greate sacrifice and a feeling of giving back to community, there might be very few peope in world who does this...."विद्या का दान ही सर्वोत्तम दान होता है" Hats Off to you man, Salute from 10+ yrs exp guy from BLR, India..

    • @shivammittal344
      @shivammittal344 15 днів тому

      bhai ye sab bakchodi likhna band kardo , aur padhai kar le thoda

  • @sush9889
    @sush9889 4 роки тому

    u r a genius man ! aap brute se optimal tak le jaate ho, ye aapki bahot achchi habit hai.

  • @yasinsherif8875
    @yasinsherif8875 Місяць тому

    i am final year student your video really helps me to understand the logics

  • @shubhigupta5689
    @shubhigupta5689 3 роки тому +3

    The way you explain, makes everything easy ❤❤

    • @imshivendra
      @imshivendra 2 роки тому

      Bhaiya what is written inside for loop(auto:it) I'm unable to understand

  • @yashwanthyerra2820
    @yashwanthyerra2820 День тому

    maximum element should be initialized with Integer.MIN_VALUE if negative also considered

  • @KarthikNandam-xs4qn
    @KarthikNandam-xs4qn 18 днів тому

    int maxSubArray(vector& nums) {
    int m = nums[0];
    int sum = 0;
    for (auto a : nums) {
    sum += a;
    m = max(m, sum);
    if (sum < 0) sum = 0;
    }
    return m;
    }
    beats 98% 🕺✅

  • @AngadSingh97
    @AngadSingh97 3 роки тому +1

    Thank you bhai, love your method of taking us from the brute force to the most optimal approach.

    • @imshivendra
      @imshivendra 2 роки тому +1

      Bhaiya what is written inside for loop(auto:it) I'm unable to understand

  • @mrankushtechnical
    @mrankushtechnical 3 роки тому +12

    Thank u striever..❤️

    • @imshivendra
      @imshivendra 2 роки тому

      Bhaiya what is written inside for loop(auto:it) I'm unable to understand

    • @pranav288
      @pranav288 2 роки тому

      @@imshivendra just an alternative for (int i=0; i

    • @imshivendra
      @imshivendra 2 роки тому

      @@pranav288 Thanks

  • @avniagarwal2295
    @avniagarwal2295 Рік тому

    The best teacher a CS student can ever have💕💕

  • @padmalayajena3593
    @padmalayajena3593 3 роки тому +2

    Thanks bro. Your explanation is far better than gfg's own explaination video.

  • @agyaani8060
    @agyaani8060 3 роки тому

    Here for loop for Brute force solution will be--->
    for(int i=0; i

    • @agyaani8060
      @agyaani8060 3 роки тому

      Is this brute force solution is applicable for all these problems---->
      Kadane's Algo,Largest Subarray with sum 0, Subarray with sum 0, Subarray with given sum?????

  • @Anonymous-wu8ry
    @Anonymous-wu8ry 2 роки тому

    best explanation. i have checked other videos but it was quite confusing

  • @thegoldenagelegendz4425
    @thegoldenagelegendz4425 4 роки тому +2

    You are a very good explainer.
    Thanks.

  • @shravanip308
    @shravanip308 2 роки тому +1

    Brute force approach for this problem can be done in O(n^2) time

  • @saravananjagadeeesan593
    @saravananjagadeeesan593 3 роки тому +1

    I am a beginner in cp and your videos are really helpful and informative. Thanks a lot, :))).Pls do make a lot of videos

  • @huteshvidhate
    @huteshvidhate Рік тому +1

    Here is the correction in the code,if all elements are negative then it returns negative number,so if(maxi

  • @roushanraj8530
    @roushanraj8530 4 роки тому +2

    Thank you adding code at last, this help us, if we find any problem during our own implementation, thank you brother
    Make explanation video for all SDE sheet questions

    • @random.__..
      @random.__.. 3 роки тому +1

      Where I can find that sde sheet ?

    • @rupampakhira8132
      @rupampakhira8132 3 роки тому

      @@random.__.. check the description box

  • @bharathKumar-or6gd
    @bharathKumar-or6gd 2 роки тому

    superb explanation brooooooo , without seeing code, written logic

  • @kausikmahata8740
    @kausikmahata8740 4 роки тому +1

    We need to arrange the code a little bit more
    What if all the elements turn out to be -ve, and everytime sum will be improved to 0 and hence the maxi also...
    Thanks dada for your valuable time and suggestions and that are lot for us...thank u...

    • @takeUforward
      @takeUforward  4 роки тому

      Read the comments, already answered!

  • @vineshkumar6886
    @vineshkumar6886 4 роки тому +2

    understood all (1-4) the problem

  • @ravikarajput2473
    @ravikarajput2473 2 роки тому +1

    to deal with cases like [-1,-2]; max = maximum of value in array

  • @shivamarora7050
    @shivamarora7050 4 роки тому +1

    Bro You are doing great for those who are not able to purchase costly DSA courses of CN and CB. KEEP IT UP.

  • @VISHALTHAKUR-gg3dg
    @VISHALTHAKUR-gg3dg 4 місяці тому

    Just addicted to your videos It's Raining outside and here raj said "i hope you doing extremely well" 😊😊

  • @bhaveshkumar6842
    @bhaveshkumar6842 3 роки тому

    You have explained this algorithm so lucidly. Thank you! :)

  • @VishalGupta-xw2rp
    @VishalGupta-xw2rp 2 роки тому

    For the question where we had to return sub array with maximum sum.... I thought of using map to put that vector carrying subarray to that maxi variable
    mpp[maxi] = vector;
    then returning mpp[maxi];

  • @hqhqyumm
    @hqhqyumm 2 роки тому +1

    there is a little error as our code assumes that the given array must have a non negative sum for a sub sequence . In the end we should filter out the output by checking weather it doesn't return a max sum as negative .................
    add these at the end
    if(maxi "greater than" 0) return maxi;
    else return 0;

  • @jaiminsolanki5478
    @jaiminsolanki5478 4 роки тому

    My Day Starts with your video , learning something new each day...
    Thankyou brother..!

  • @Sumanth_Siddareddy
    @Sumanth_Siddareddy 6 місяців тому

    Understood. Thank you for explanation.

  • @AMITKUMAR-nq8zl
    @AMITKUMAR-nq8zl 2 роки тому

    got this sir after a long research thankyou.

  • @sahilchoudhary1473
    @sahilchoudhary1473 4 роки тому +3

    you are doing great job man this list is very good to cover almost every concept.

    • @imshivendra
      @imshivendra 2 роки тому

      Bhaiya what is written inside for loop(auto:it) I'm unable to understand

  • @konankikeerthi
    @konankikeerthi 5 місяців тому

    thanks for your efforts bro. understood clearly

  • @suguruchhaya3194
    @suguruchhaya3194 3 роки тому

    I noticed how many videos explain the process by saying temporaryMax = max(temporaryMax+arr[i], arr[i]). At first I was a little confused between what striver
    explained and all the other guys but when I think about it, max(temporaryMax+arr[i], arr[i]) == arr[i] if and only if temporaryMax < 0 because if temporaryMax carries a negative value, there is no point adding it. So striver is basically touching on the same thing.

  • @ranasauravsingh
    @ranasauravsingh 2 роки тому +1

    UNDERSTOOD... !
    Thanks striver for the video... :)

  • @stith_pragya
    @stith_pragya 2 роки тому

    Thank You so much Striver...............🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻

  • @shubhamrajput2372
    @shubhamrajput2372 2 роки тому

    suppose [-2] input liye then expected output -2 aana chahiye but 0 aa rha jo ki galat h

  • @VivekJaviya
    @VivekJaviya 3 роки тому +1

    2:59 For middle optimal we can also do by sorting and sum of all positive numbers or last number.

    • @takeUforward
      @takeUforward  3 роки тому +13

      If you sort it wont be subarray anymore!

  • @random.__..
    @random.__.. 3 роки тому

    class Solution {
    public int maxSubArray(int[] nums) {
    int maxSum= nums[0];
    int currentSum= maxSum;
    for(int i=1; i

  • @thegeekb0y
    @thegeekb0y 3 роки тому

    Best video on Kadane's Algo. Keep up the good work. Shakespeare's will keep criticising!

  • @gunnavinayreddy572
    @gunnavinayreddy572 Рік тому +1

    excellent brooo....nice explanatation

  • @ojasvisharma2751
    @ojasvisharma2751 4 роки тому +2

    This series is as awesome as it gets!

  • @NazeerBashaShaik
    @NazeerBashaShaik 10 місяців тому

    Great explanation, thank you.

  • @yeswanthh5068
    @yeswanthh5068 2 роки тому +1

    Thankyou understood 🙂🙂💚💚

  • @anandhisubramaniam6630
    @anandhisubramaniam6630 3 роки тому

    Best explanation ever...kudos ✨

  • @nileshsinha7869
    @nileshsinha7869 3 роки тому

    Thanks again striver bhai ..thora time baad krne baitha bhul gya tha thora ..dobara se dekha phir ek naya chiz smzh aaya isi mein ❤❤👌

  • @sonipratham9411
    @sonipratham9411 Рік тому

    Very Well Explained 👍👍

  • @ascar66
    @ascar66 2 роки тому

    Thank you, clear enough.

  • @-CYSAIANUSHA
    @-CYSAIANUSHA 2 роки тому

    Very useful video. Crisp but effective

  • @MultiFacebookers
    @MultiFacebookers 2 роки тому +1

    Can anybody tell me the modification in this approach if all the elements are negative? Should we first check if all elements are positive or negative and then proceed accordingly?

  • @makehack0705
    @makehack0705 Рік тому

    So we need to add extra if condition

  • @saiakshagn3553
    @saiakshagn3553 2 роки тому +1

    //C Program(Applicable for both positive and negative numbers)
    #include
    int main()
    {
    int a[50],i,n;
    int maxsum,cursum=0;
    scanf("%d",&n);
    for(i=0;i

  • @ritikashishodia675
    @ritikashishodia675 2 роки тому +1

    Thank u bhaiya great 👏👏👏

  • @Skkskk702
    @Skkskk702 4 роки тому

    thank you..this is helpful in clearing DSA basics

  • @1tav0
    @1tav0 2 роки тому

    Great explanation mr

  • @sameerchoubey9724
    @sameerchoubey9724 4 роки тому

    int maxSubArray(vector &arr) {
    int current_max = arr[0], max_so_far = arr[0];
    for (auto it : arr) {
    current_max = max(current_max + it, it);
    max_so_far = max(max_so_far, current_max);
    }
    return max_so_far;
    }

  • @aakashchaudhary3215
    @aakashchaudhary3215 4 роки тому +2

    Bro .. please keep uploading .. we are loving your videos..

  • @anshikadixit3091
    @anshikadixit3091 Рік тому

    excellent explaination thankyou

  • @abhaythakur2597
    @abhaythakur2597 Рік тому

    very well explained

  • @sagar1287
    @sagar1287 3 роки тому

    thanku bhai It was easy to understand
    you are great

  • @sonalisaxena22
    @sonalisaxena22 4 роки тому +1

    very very very very well explained !! thankyou

    • @takeUforward
      @takeUforward  4 роки тому +1

      Glad it was helpful!

    • @sonalisaxena22
      @sonalisaxena22 4 роки тому

      @@takeUforward please complete one by one total 180 questions....

  • @raihanar5323
    @raihanar5323 2 роки тому

    Best solution ever

  • @cinime
    @cinime 2 роки тому

    Understood! So amazing explanation as always, thank you very much!

  • @gokulsrinivasan8563
    @gokulsrinivasan8563 Рік тому

    Awesome video Stiver, thanks

  • @rohitpawar4096
    @rohitpawar4096 4 роки тому

    We all learning something new that all becoz of your video's

  • @saikoushik4064
    @saikoushik4064 3 місяці тому

    what if they want indices in which maximum sum is occurring?

  • @EdwinaNeheru69
    @EdwinaNeheru69 4 роки тому +1

    Bhaiya pls prepare a java Sol along with cpp it will be very helpful ...by the way grt work.😇😇😇😇😇

    • @takeUforward
      @takeUforward  4 роки тому

      Savi, can you please see the entire video? Java solution is there :)

    • @EdwinaNeheru69
      @EdwinaNeheru69 4 роки тому

      @@takeUforward sir I am really sorry actually vid suddenly stopped (due to buffer I guess ) it was over ...my bad😔😔😔

  • @simple_user000
    @simple_user000 3 роки тому

    Best explanation brother.......

  • @manikgoyal8026
    @manikgoyal8026 Рік тому

    very helpful bhaiya , great

  • @tamilmukbang3789
    @tamilmukbang3789 6 місяців тому

    understood..thank you bro

  • @suryansh70
    @suryansh70 2 роки тому

    very good explanation

  • @renaissancesuperman4086
    @renaissancesuperman4086 4 роки тому

    Your make coding Fun bro! Thanks for the simplicity

  • @Arun-tq9qr
    @Arun-tq9qr 3 роки тому

    Thanks for your clear explanation 🙏🏻👌🏻.

  • @reachrishav
    @reachrishav 3 роки тому +1

    Great.. What if we want to return the subarray too?

    • @takeUforward
      @takeUforward  3 роки тому

      Put some if else.. will update the code in link soon

  • @abhisheksahani4481
    @abhisheksahani4481 3 роки тому

    Really worth it for quick learning

  • @shycoder6332
    @shycoder6332 4 роки тому

    Thank you so much sir. Completely understood.

  • @darshantank554
    @darshantank554 2 роки тому

    1D DP is also a good solution

  • @ChetanvarmaAtla
    @ChetanvarmaAtla 25 днів тому

    how should i remember all this algorithms which ur telling in every video like how buddy? should i note it down and revise after few days?

  • @madhan8745
    @madhan8745 3 місяці тому

    Thank you

  • @infinioda108
    @infinioda108 4 роки тому +2

    Sirji great videos very helpful plz continue to upload some more 🔥🔥

    • @imshivendra
      @imshivendra 2 роки тому

      Bhaiya what is written inside for loop(auto:it) I'm unable to understand

    • @vinayakgs1665
      @vinayakgs1665 2 роки тому

      @@imshivendra auto takes the datatype whichever it is there over, and it itereates the whole loop

  • @70_it_radheshyambhagat63
    @70_it_radheshyambhagat63 2 роки тому

    Awesome explanation bhiya 😊😊❤️

  • @sahilbheke4083
    @sahilbheke4083 Рік тому

    some time i forget to like but that doesn't mean you are not best you are best and best does not depend of count of likes

  • @HarianshSehgal
    @HarianshSehgal Рік тому

    @takeUforward the solution does not cover the case when all elements are negative, it will return 0 instead of the smallest element.