Maximum Sum Rectangle In A 2D Matrix - Kadane's Algorithm Applications (Dynamic Programming)

Поділитися
Вставка
  • Опубліковано 19 вер 2024
  • Free 5-Day Mini-Course: backtobackswe.com
    Try Our Full Platform: backtobackswe....
    📹 Intuitive Video Explanations
    🏃 Run Code As You Learn
    💾 Save Progress
    ❓New Unseen Questions
    🔎 Get All Solutions
    Question: Given a 2D matrix with integer values (and including at least 1 positive value) find the sub-rectangle with the largest sum.
    I want to step you through all of the tough mental leaps to solve this problem.
    Complexities
    Let rows = the number of rows
    Let cols = the number of columns
    Naive Runtime: Ω(rows^2 * cols^2)
    Explanation:
    There are rows * cols possible start points and for each rows * cols possible start points we will do O(rows * cols) work, this causes us to have our time lower bounded by the amount of time it takes to explore all top left and bottom right combinations so that we can explore all 2D rectangles in the matrix.
    This is not even including getting the sum for each 2D rectangle we set bounds for (we can do it in O(rows).
    Similar to this problem leetcode.com/p...
    Optimal Solution Runtime (2D Kadane's): O(cols^2 * rows)
    We will try all combinations of left and right ending points for the possible 2D rectangle.
    For that O(col^2) work we will do O(row) work to run Kadane's on the row sum cache (for each left-right combination of the possible final rectangle).
    So the cumulative work will be O(cols^2 * rows).
    Space will be O(rows) because of the vertical rows sum cache.
    ++++++++++++++++++++++++++++++++++++++++++++++++++
    HackerRank: / @hackerrankofficial
    Tuschar Roy: / tusharroy2525
    GeeksForGeeks: / @geeksforgeeksvideos
    Jarvis Johnson: / vsympathyv
    Success In Tech: / @successintech

КОМЕНТАРІ • 280

  • @BackToBackSWE
    @BackToBackSWE  5 років тому +36

    Table of Contents:
    Geekin' 0:00 - 0:16
    Going Meta 0:16 - 1:08
    The Problem Introduction 1:08 - 2:47
    Beginning of Brute Force Walkthrough 2:47 - 5:17
    We Try The Next Top Left Planting 5:17 - 5:57
    Analyzing The Brute Force's Runtime 5:57 - 6:33
    Bounding The Work In Choosing Bottom Right Corners 6:33 - 7:31
    Deriving A Lower Bound For The Brute Force 7:31 - 8:51
    The Lower Bound For The Brute Force 8:51 - 9:38
    Can We Do Better? 9:38 - 9:43
    Beginning The Optimal Solution Walkthrough 9:43 - 10:18
    Explaining The Algorithm 10:18 - 12:26
    How Do We Pick An Optimal Top & Bottom For The Max Rectangle? 12:26 - 14:28
    Walkthrough Continues 14:28 - 20:22
    We Find The Best Rectangle 20:22 - 21:19
    Walkthrough Continues 21:19 - 22:55
    Recapping What Just Happened 22:55 - 23:50
    Deriving The Optimal Solution Time Complexity 23:50 - 25:38
    Space Complexity 25:38 - 26:07
    Wrap Up 26:07 - 26:46
    Mistakes:
    11:17 -> The entry at index 3 in the runningRowSums array should be -8, not 8. Sorry.
    Yeah, the LED light is reflecting sharply off my glasses, I'll get something to diffuse the light better next time.
    The code for this problem is in the description. Fully commented for teaching purposes.

    • @Happy-on2is
      @Happy-on2is 4 роки тому +1

      Hello bro I don't find any description?
      It was a good effort thankyou.

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

      The repository is deprecated, we only maintain backtobackswe.com now.

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

      @@BackToBackSWE This code is not even there in backtobackswe premium member access. Could you plz provide?

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

      @Back To Back SWE i couldnt find code there as well

  • @IamSinghJaskaran
    @IamSinghJaskaran 5 років тому +95

    you good with code
    you are no fraud
    explain very well
    Knowledgeable as hell

    • @BackToBackSWE
      @BackToBackSWE  5 років тому +5

      thanks

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

      @@BackToBackSWE that's a poem haha

    • @0anant0
      @0anant0 3 роки тому +3

      Is writing Haikus your 'thing',
      Mr Jaskaran Singh? :-)

  • @abhinavsingh4221
    @abhinavsingh4221 5 років тому +33

    Buddy the way you explain makes brute-force also look awesome 😂😂 You are the best teacher!

  • @suraj8087
    @suraj8087 5 років тому +37

    The Thought process is what i needed. Thank You .

  • @Official-tk3nc
    @Official-tk3nc 4 роки тому +57

    if you are watching this in lockdown you are one of the rare species on the earth . many students are wasting their time on facebook, youtube, twitter, netflix, watching movies playing pubg, but you are working hard to achieve something . ALL the best ...nitj student here

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

      an inspiration

    • @mradulagrawal1579
      @mradulagrawal1579 4 роки тому +13

      Bro yahi tune tushar roy ke video me bhi likha hai naa 😜

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

      @@mradulagrawal1579 😂😂😂😂

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

      why there is even a need to tell from which college u are...

  • @mayukhchanda5805
    @mayukhchanda5805 4 роки тому +23

    This is such a smart and beautiful application of Kadane's algorithm. And explained so patiently and I'm such detailed manner, it was pure bliss to watch. Thank you for making such videos.

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

    Normally, I skip videos that explain a concept in more than 10 minutes as usually they talk a lot but say very little. I’m glad I stayed for the long haul on this one Lol
    Excellent explanation. You speak clearly, make pauses, and do not leave anything to chance. Thank you!
    Ps- I don’t recommend starting your videos with those 2 guys goofing around. For the people who come across your channel for the very first time (such as me right now), this is a very good way to send off potential viewers. I almost gave up until you appeared.

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

      I do not remember a single word I said in this video whatsoever, glad it helped. And yeah, I am fully aware of this phenomenon, these older videos were around when no one watched.

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

    Your channel has one of the best explanations for every question. The way you describe the thought process behind and cover everything from brute force to explaining about complexities makes it way easier to understand. Thanks a lot!

  • @adamyamishra9179
    @adamyamishra9179 4 роки тому +9

    I've been here watchin you almost an year now, I've literally recommended your channel to everyone at my college NIT Jalandhar, one of the colleges of National Importance in India. We love you bro, your're the best thing that could have ever happened to UA-cam!

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

      thanks and nice, and haha thanks

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

      Lol why the flex though? NIT Jalandhar is a shit tier 2 college no company even cares about to visit.

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

      "NIT Jalandhar, one of the colleges of National Importance in India" , one question, Why?😂

  • @tom0313choi
    @tom0313choi 5 років тому +8

    Best explanation I have ever found

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

    You did a really good job by explaining what Tushar didn't. Finally understood this problem pretty well !

  • @srinaath9845
    @srinaath9845 5 років тому +6

    Wow thanks man. You explain so good that it's not even necessary to see the code for implementing 👌👏

    • @BackToBackSWE
      @BackToBackSWE  5 років тому

      aw thx

    • @maripaz5650
      @maripaz5650 5 років тому +2

      So true. I'm binging these videos rn to study for my algorithms exam next week. I'm feeling better since I'm actually starting to understand dynamic programming. Thank you!

    • @BackToBackSWE
      @BackToBackSWE  5 років тому

      @@maripaz5650 nice

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

    your subscription should grow 10 times more, your teaching is clear and easy-to-understand, concise as gold.

  • @jishulayek8252
    @jishulayek8252 5 років тому +7

    Thanks for uploading this. One of the best explanation I have came across. Keep up the good work.

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

    I've been sitting trying to solve this as my algorithm assignment and all I could get after 5 hours of staring was the brute force solution. This opened my "third" eye. :D Great videos, thank you very much

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

    One of best explanation available online.

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

    thank you, implementing the algorithm felt so soft after your explanation, keep up

  • @Maholain
    @Maholain 5 років тому +4

    Thank you so much for putting out these videos! You explain the thought process of coming up with the answer (arguably the most important part of the process; converting to code is usually quite easy once you understand the problem) way, way better than any other channel I've come across.
    Tiny mistake I noticed: at 13:00, the last entry of running sum should be -8, not 8. This threw me off a little when you said 6 was the largest contiguous subarray.

    • @BackToBackSWE
      @BackToBackSWE  5 років тому

      Thank you, and got it, I updated the teacher's notes.

  • @favs5286
    @favs5286 5 років тому +2

    initially i thought this would be the same as Tushar Roy's tutorial vid, turns out it wasn't! the good part is you really added more to what was already explained by Tushar, great job!

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

    I love the passion you are trying to explain and it's all crystal clear. Love your channel, good job mate!

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

    Clear explanations! Thank you so much!

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

    What a clear and awesome explanation. The meat of the video starts at 10 min mark. That's where the row sum array is introduced. Left, Right, Top, Bottom and running row sum is what's needed
    Anytime we are trying to solve a 2D sum problem we need to check continuous sum of a 1D array ( the row sum in this example). In brief anytime we have an 'N' dimensional structure we will need to look at (N-1) running sum structure.

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

    Great job! A nit to help others: In the running row sum for the first col when L = R= 0 at 14:00, the last row in the blue array has 8 while the original matrix has -8. Confuses why 6 is the largest when compared to 8, if you're caught off-guard! :-)

  • @heyitsnikhil7956
    @heyitsnikhil7956 5 років тому +4

    Best explaination so far. Im going to watch the whole playlist in sequence. Im really enjoying it. 😮🙌
    Why not sort the playlist on the basis of difficulty for people watching in sequence.. ✌️

  • @lemonginger001
    @lemonginger001 5 років тому +17

    man start taking system design topics as well .. u explain really well

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

    Very underrated channel...Amazing videos

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

    This explanation was very helpful and clear. You have a natural talent for teaching.

  • @hullyoung
    @hullyoung 5 років тому +2

    Thanks for the clear explanation, love that you paced the video really well

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

    Really good videos. I am prepping for coding interviews and I guess this is one of the best resources that one can go through.

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

    I just hit the gold-mine of Coding..... This is priceless... I'm very very thankful to the B2B_SWE guys...

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

      lol hi

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

      @@BackToBackSWE hi... I'm a final year undergrad student preparing for interview. And B2B_SWE is the best place because of its in-depth analysis of the problems and solutions is much needed to develop problem solving ability... Thanks man. By the way, where are you from, USA?

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

      @@debayondharchowdhury2680 sure and yes the united states

  • @VishalKumar-kr9me
    @VishalKumar-kr9me Рік тому

    You made my day, I saw so many posts and videos none of them explained why we are doing.
    I have been following you since 2019

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

    LOved it bro.... this content deserves to be paid. clear,concise set of words and what not.

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

      thanks - and it is we have backtobackswe.com

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

    Bro just keep up the good work. The approach of solving the problems is really great.

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

    best tutorial of the question

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

    We need more people like you. Big thank from Vietnam!

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

    i literally never look at the code as the explanation itself is soo good.

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

    I have a question. If we knew that N or M is bigger. Would it help to transpose the matrix so that there are less running row sums to compute? If so, would the speedup be significant? My guess would be that it would make sense for matrices that have M >> N. Also it appears, that we would only save on space complexity, not time complexity in particular.

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

    your explanation is soooooo CLEAR and THOROUGH and you INDEED help me. Thank you for your sharing. :)

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

    explanation is brilliant ,wow it seems so easy when u explained,great job,please keep doing this

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

    awesome interpretation. Excellent job!

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

    Best DSA channel on the planet!

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

    Damn! I Love you man! Such crystal clear explanations!

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

    Was looking for the thought process for a similar problem. Found gold.

  • @dikshantyadav1110
    @dikshantyadav1110 5 років тому +3

    dude, you are just fab with explanation's and time complexity

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

    Dude i wanna thanks you clear explanation and you really put work in ! and subscribed hope you keep posting algorthime problems

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

    it says the code in the description, where is the description ? Thank you for your amazing explanation . This is the best I've heard .

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

      The repository is deprecated - we only maintain backtobackswe.com now. and thanks

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

      @@BackToBackSWE Thank you

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

    Great explanation on this one! Coming up with a solution and coding it up in 45 minutes seems unreasonable. Hoping people aren't actually being asked this in interviews!

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

    Wow! A hard problem turned into an easy problem now
    Great explanation!!!!!

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

    Like and comment-done
    Prerequisites done for watching video ;)

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

    omg such a fantastic explanation.....hats off man.

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

    one of the best explanation i came so far

  • @shubhamjindal9214
    @shubhamjindal9214 5 років тому +1

    could not have got any better ...!
    nailed it ..!!

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

    The brute force time complexity is O(row^3* col^3).

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

    This video is so great, really made the hard problem easy to understand.

  • @AnhLe-hc8qm
    @AnhLe-hc8qm 4 роки тому +1

    Thanks for your clear explaination !!!

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

    thanks man that was a great explanation

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

    Best video I have ever seen from u and also it's good that u are telling the time complexity at the end of video

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

    Very genuine and i love the way you explain.. it leverages the thought process which really matters rather memorising!!!!

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

    Thanks for your explanation!

  • @孫傅康
    @孫傅康 6 місяців тому

    NIce explanation! Thank you so much!

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

    awesome explanation !!!!

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

    your video is good,
    gfg article does not explain the solution to this question properly.

  • @VIJAYKUMAR-tn1kr
    @VIJAYKUMAR-tn1kr 3 роки тому

    So much helpful.Thank you .

  • @Mohit-cn2us
    @Mohit-cn2us 3 роки тому +1

    but you are not decrementing top left point, so how come you are checking each of the possible rectangle sum in DP approach ?

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

    Wonderful! Thanks for putting in all the effort!

  • @ManishSharma-fi2vr
    @ManishSharma-fi2vr 3 роки тому

    DRY run is awesome!

  • @puperhacker2150
    @puperhacker2150 5 років тому +1

    Excellent video. Thanks!

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

    Wow, ThankYou. You rock.

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

    "We will try all combinations of left and right ending points for the possible 2D rectangle." - Can we use range sum querying per row to reduce the time complexity to O(rows*cols)?

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

      I'm not sure don't remember the problem much

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

      @@BackToBackSWE I was referring to this - ua-cam.com/video/ZMOFmHBVEcg/v-deo.html

  • @j.c9858
    @j.c9858 3 роки тому

    i would say this is the best explanation I found so far, thank you for sharing!

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

    It turned out awesome ♥️

  • @ManishSharma-fi2vr
    @ManishSharma-fi2vr 3 роки тому

    Thanks for this kind of explanation!

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

    Dude, you are the best

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

    another amazing explanation

  • @olicmoon
    @olicmoon 5 років тому +1

    Nicely explained

  • @naveenmeena1832
    @naveenmeena1832 5 років тому +1

    Hats Off dude. Gr8 way of explanation Tushar Roy can learn a thing or two from you

  • @bekzatongdassynov827
    @bekzatongdassynov827 11 місяців тому

    I think we could also do prefix sum on rows to do sums faster

  • @VipinKumar-us1sr
    @VipinKumar-us1sr 2 роки тому +1

    I would like to meet you and thanks for this special video...I was like wooowww

  • @ujjawaltyagi302
    @ujjawaltyagi302 5 років тому +2

    I don't think your code will work when all entries are negative as your kadanae function returns values greater than or equal to zero.
    if you substitute by this it should do fine.
    public int maxSubArray(int[] nums) {
    int maxEndingHere=0;
    int max=Integer.MIN_VALUE;
    int cS=0,cE=0;
    int gS=-1,gE=-1;
    for(int i=0;imaxEndingHere+nums[i]){
    cS=i;cE=i;
    maxEndingHere=nums[i];
    }else{
    cE=i;
    maxEndingHere=maxEndingHere+nums[i];
    }
    if(maxEndingHere>max){
    gS=cS;gE=cE;
    max=maxEndingHere;
    }
    }
    System.out.print(gS+" "+gE);
    return max;
    }
    great explanation btw.

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

    Bruhhhhhh... you're awesome!! Totally loved the you taught. Thanks much for this video!!

  • @Junaid.K
    @Junaid.K 4 роки тому +1

    code is not in the description.
    but anyways video is excellent.

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

      The repository is deprecated - we only maintain backtobackswe.com now.

  • @abhigupta6681
    @abhigupta6681 5 років тому +1

    your content is great. Thank you

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

    You are amazing.TYSM

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

    can u please make a video on how to find kth largest element in a row wise and column wise sorted matrix using binary search

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

    You are the best bro !

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

    HEY JOHN LEGEND>>NICE WORK BUDDY>>YOU ARE A GREAT SINGER INDEED

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

    For Time Complexity -
    Since we are finding all pairs of cols, that makes it O(cols^2). And with in each pair, we will do sequential passes over rows right? One pass to add new elements to update running row sum and the other pass to find max using Kadane's algorithm. That makes the passes as O(2*rows). Since 2 is constant, the final TC becomes O(cols^2 * rows). Is this right?
    Writing this just for clarification.

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

    Great video

  • @Ayushkumar-xj9vl
    @Ayushkumar-xj9vl 4 роки тому +1

    I wish we can meet someday. Thank you for your efforts !!

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

    Great work dude! Nice one :-)

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

    Sorry where is the code? Great video, it helped me so much!

  • @bhavukgarg3619
    @bhavukgarg3619 5 років тому +1

    Nice explanation

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

    You were right.. tushar was missing why kadane was used

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

      Thank you, glad you liked it 😀
      Do check out backtobackswe.com/platform/content
      and please recommend us to your family and friends 😀

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

    Thank u, u are incredible

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

    Damn you reply to every single comment, also the new setup is quite good.

  • @rishabhagnihotri7585
    @rishabhagnihotri7585 5 років тому +2

    u are awsome man!

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

    wonderful explanatrion

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

    I have a quick modification questions.
    If we wanted to find squares instead of rectangles, how would you approach this problem?
    I am not able to figure that out

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

      im not sure dont remember tbh

    • @Jay-dm4id
      @Jay-dm4id 3 роки тому

      Similar to rectangle but only restriction is instead of kadane,you need to find max subarray of size K( K = R-L+1) in the sum column. This can also be done in o(m) time,so complexity is same.

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

    absolutely awesome

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

    best explaination bro