Maximum Product Sub-array (LeetCode 152) | Full Solution with animations and proof | Simplified

Поделиться
HTML-код
  • Опубликовано: 30 июл 2024
  • To see more videos like this, you can buy me a coffee: www.buymeacoffee.com/studyalg...
    Actual problem on LeetCode: leetcode.com/problems/maximum...
    Chapters:
    00:00 - Intro
    00:45 - Problem Statement and Description
    02:43 - Breakdown the problem into parts
    07:36 - Proving the idea
    11:32 - Dry-run of Code
    13:35 - Final Thoughts
    📚 Links to topics I talk about in the video:
    LeetCode Problems: • Leetcode Solutions
    Kadane's Algorithm: • Maximum Sub-Array Sum ...
    Divide and Conquer: • Divide and Conquer alg...
    📘 A text based explanation is available at: studyalgorithms.com/array/lee...
    Code on Github: github.com/nikoo28/java-solut...
    Test-cases on Github: github.com/nikoo28/java-solut...
    📖 Reference Books:
    Starting Learn to Code: amzn.to/36pU0JO
    Favorite book to understand algorithms: amzn.to/39w3YLS
    Favorite book for data structures: amzn.to/3oAVBTk
    Get started for interview preparation: amzn.to/39ysbkJ
    🎥 My Recording Gear:
    Recording Light: amzn.to/3pAqh8O
    Microphone: amzn.to/2MCX7qU
    Recording Camera: amzn.to/3alg9Ky
    Tablet to sketch and draw: amzn.to/3pM6Bi4
    Surface Pen: amzn.to/3pv6tTs
    Laptop to edit videos: amzn.to/2LYpMqn
    💻 Get Social 💻
    Follow on Facebook at: / studyalgos
    Follow on Twitter at: / studyalgorithms
    Follow on Tumblr at: / studyalgos
    Subscribe to RSS feeds: studyalgorithms.com/feed/
    Join fan mail: eepurl.com/g9Dadv
    #leetcode #programming #interview

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

  • @nikoo28
    @nikoo28  Месяц назад +4

    As of this writing LeetCode added a new test case which cause the above code to fail. The logic is still correct though.
    The test case fails because of overflow error. With just a small fix, the code still works. Have a look at the updated code on my Github link :)

    • @Armaan_Punia_
      @Armaan_Punia_ 26 дней назад +2

      [0,10,10,10,10,10,10,10,10,10,-10,10,10,10,10,10,10,10,10,10,0] this is the testcase for which it fails; can you tell what the fix is sir?

    • @nikoo2805
      @nikoo2805 26 дней назад +1

      @@Armaan_Punia_that is what I exactly did in the updated code. Did you have a look?

    • @Armaan_Punia_
      @Armaan_Punia_ 25 дней назад +1

      @@nikoo2805 yesterday I had removed what I thought was redundant, 190/191 test cases then passed, now all did! thank you

    • @katerghost642
      @katerghost642 12 дней назад

      @@Armaan_Punia_ bhai iska answer mille toh reply krdena salla do ghanta ho gya h

    • @unknownman1
      @unknownman1 3 дня назад

      @@katerghost642 class Solution {
      public int maxProduct(int[] nums) {
      long leftproduct = 1;
      long rightproduct = 1;
      long ans = nums[0];
      for(int i=0; i

  • @hoddybhaba6704
    @hoddybhaba6704 Год назад +3

    Fantastic explaination👏👏👏You deserve more likes, more views and definitely more subscribers!!!

  • @sayedmahmudulalam2738
    @sayedmahmudulalam2738 9 месяцев назад +7

    This is the simplest and most intutive solution.

  • @andreabad3518
    @andreabad3518 5 месяцев назад

    I was really struggling to understand some other solutions for this problem that used dynamic programming, but you really made it simple to understand! Thanks!

  • @yashbhinwal2801
    @yashbhinwal2801 Год назад +2

    you did a great job explaining this concept, really helpful!!

  • @vineetkumar2899
    @vineetkumar2899 Год назад +2

    the way you explain things are just Awesome.

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

    Clean , crisp & most underrated !

  • @subhadippahari185
    @subhadippahari185 Год назад +7

    What an explanation. Really mind-blowing. Saw other videos on the same topic, but this is a really whole different level of logic.

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

    Very clean , clear and simple explanation.

  • @maggiesayabie
    @maggiesayabie Год назад +2

    I love your explanation!

  • @ghanashrim2839
    @ghanashrim2839 Год назад +3

    Your explanations are so on point yaar... I've been binge-watching all your videos...!
    Please make more.

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

      Thank you so much 😀

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

    I do really like your solution, it is so much easier to understand. Thank you

  • @tejasavhad4010
    @tejasavhad4010 11 месяцев назад +2

    Underrated channel.

  • @akhintheruvath
    @akhintheruvath 18 дней назад

    Crisp and clear explanation. Thank you bro.

  • @shushanbalayan6267
    @shushanbalayan6267 Год назад +1

    Great explanation! Thank you

  • @MinhLe-ks5en
    @MinhLe-ks5en 4 месяца назад

    This is genius. You deserve more likes and more subscribers. I love your systematic way of explaining the reasoning.

    • @nikoo28
      @nikoo28  29 дней назад

      Glad you think so!

  • @jatinkumar4410
    @jatinkumar4410 3 месяца назад +2

    amazing explanation... Thank you

  • @240SX2pAc
    @240SX2pAc 8 месяцев назад +1

    Wonderful solution, thank you

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

    Very good brother. Thank you.

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

    🎉Great Explaination 😮

  • @jironymojirolamus913
    @jironymojirolamus913 5 дней назад

    Great explanation, thanks! I actually solved it in a similar way, but was unsure if it's a way to go since everyone is talking DP nowadays.

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

    Thank you my friend simple and easy

  • @ashwinnair1035
    @ashwinnair1035 4 месяца назад

    Great explanation sir

  • @oknokok
    @oknokok 14 дней назад +1

    simple and exellent explanation

  • @KhyleSewpersaud
    @KhyleSewpersaud 7 дней назад

    fantastic solution

  • @samiramousaie1158
    @samiramousaie1158 8 месяцев назад +1

    your explanation is awesome. I totally understand it.

    • @nikoo28
      @nikoo28  8 месяцев назад

      Awesome, thank you!

  • @rajalakshmirajasekar260
    @rajalakshmirajasekar260 Год назад +5

    Bro ur explanation is awesome!! I am able to think the flow of program and build the intuition easily.. one request bro Plz upload recursion vdos.. Thank you!!

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

      i have made several videos that use recursion. Check out the basics here: ruclips.net/video/FTTHkmnvzlM/видео.html

  • @avinashabhi95
    @avinashabhi95 Год назад +1

    Your explanation is superb. Subscribed.

    • @nikoo28
      @nikoo28  11 месяцев назад

      Welcome aboard! 😄

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

    bhai tum kya bande ho yaar… when other top teachers and youtubers fail to explain the hardest problems, you explain those problems so easily somehow….. Man you deserve so much appreciation… Great work bhai..so much inspired by you… Really top-notch explanations.

    • @nikoo28
      @nikoo28  29 дней назад

      that is so kind of you...please share and support as much as you can :)

  • @amitmandal5842
    @amitmandal5842 7 месяцев назад +1

    Excellent explanation. I mean, you made question easy.. valaaaah😊

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

      Glad to hear that

  • @maherworld1
    @maherworld1 10 месяцев назад +2

    AWESOME! God bless u

    • @nikoo28
      @nikoo28  9 месяцев назад

      Thank you! You too!

  • @yadneshraut6854
    @yadneshraut6854 Месяц назад +3

    Understood this logic but it fails at last testcase of leetcode 152 so please update the logic for the testcase and code too........!!! Thank you !!

    • @nikoo28
      @nikoo28  29 дней назад +1

      since I cannot edit the video, the code has been updated in the github link :)

    • @yadneshraut6854
      @yadneshraut6854 29 дней назад

      @@nikoo28 thank you sir !

  • @tanugiri532
    @tanugiri532 4 месяца назад

    Thankyou sir ❤

  • @shreyanshgoel9757
    @shreyanshgoel9757 2 месяца назад +1

    Your solution impies that ans subarray lie either in suffix or in prefix in non zero elements are present

  • @user-zl3ju9tt2g
    @user-zl3ju9tt2g 5 месяцев назад

    this is the best simple solution even the editorial solution is nothing infront of this

    • @nikoo28
      @nikoo28  4 месяца назад

      glad you feel that way!!

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

    I LOVE UR CHANEL

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

    Too concise... Too the point.... Best explanation.... I can compare you with Striver... Though you are better than him at many places.... ❤

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

      Thanks for the view

  • @user-dg4vv5ru5h
    @user-dg4vv5ru5h 8 месяцев назад +1

    What if all elements are zero. Then it will fail?

  • @Max-tq1ig
    @Max-tq1ig 10 месяцев назад +2

    Hi, Nikhil! I understand the code and how can you get the answer by using the two comparisons from right and left, but I don't get the logical idea of pointing out that you need to remove the middle number at minute 6:26.
    Is it just an example of what should we get if you keep with odds numbers instead of an even; or just the idea of having more numbers in general? I don't understand x__x
    It's not something to will do automatically by following the code?

    • @nikoo28
      @nikoo28  10 месяцев назад +2

      you don't have to remove the middle number, we are just trying to get the maximum product. 2 negatives will give you a positive number, but 3 negatives will give you a negative number again.

  • @rahulchandak2772
    @rahulchandak2772 27 дней назад

    The logic sounds very simple but its difficult to understand for cases where the subarray does not contain the starting (leftmost) or the ending (rightmost) element. When the sub array is in between the array

  • @cagarwal
    @cagarwal 9 месяцев назад +1

    Can you explain why we need to start from both sides? I'm not able to see any benefit in starting from both sides as both eventually gives the same result.

    • @nikoo28
      @nikoo28  8 месяцев назад +1

      I don't understand...did you go though my complete video? It cannot be done if we don't go from both sides.

  • @kesharwani.prashant
    @kesharwani.prashant 6 месяцев назад

    Looks like stiver copied your exact logic:) Thanks for explaining it so clearly !

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

    what if there is no positive element in the array?

  • @kishanmishra7301
    @kishanmishra7301 Год назад +2

    Hello, Your videos are so good and the way you explain the question as well as the the solution is very nice please keep making these videos I have one request can you please explain (3. Longest Substring Without Repeating Characters) this question of leetcode

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

      i added this problem to my list... :)

  • @ashoksaipudi6999
    @ashoksaipudi6999 9 месяцев назад +1

    Hey actually its such a good explanation. but one mistake in explanation of 2nd testcase(2:10 min) there you don't take the contigous sub-array.

    • @nikoo28
      @nikoo28  9 месяцев назад +1

      i do take the contiguous sub-array

  • @user-he3hs6iy8o
    @user-he3hs6iy8o Месяц назад +2

    it fails on the last test case on leetcode

    • @nikoo28
      @nikoo28  29 дней назад

      since I cannot edit the video, the code has been updated in the github link :)

  • @gopik6202
    @gopik6202 Месяц назад +1

    class Solution {
    public int maxProduct(int[] nums) {
    if (nums == null || nums.length == 0) {
    return 0;
    }
    int maxProduct = nums[0];
    int currentMax = nums[0];
    int currentMin = nums[0];
    for (int i = 1; i < nums.length; i++) {
    if (nums[i] < 0) {
    // Swap currentMax and currentMin when encountering a negative number
    int temp = currentMax;
    currentMax = currentMin;
    currentMin = temp;
    }
    currentMax = Math.max(nums[i], currentMax * nums[i]);
    currentMin = Math.min(nums[i], currentMin * nums[i]);
    maxProduct = Math.max(maxProduct, currentMax);
    }
    return maxProduct;
    }
    } this is crt logic

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

    U shud also include bruteforce solutions

  • @TanishaVarshney-ti9yl
    @TanishaVarshney-ti9yl 4 месяца назад

    i understand the question and solution everything completely but on submitting it on leetcode after checking it twice it says wrong answer don't know why could you please tell me?

    • @nikoo28
      @nikoo28  4 месяца назад +1

      Check out the complete code on my github. Link in description. That should give you a hint.

    • @TanishaVarshney-ti9yl
      @TanishaVarshney-ti9yl 4 месяца назад

      @@nikoo28 i have tried that too but its also not working

    • @TanishaVarshney-ti9yl
      @TanishaVarshney-ti9yl 4 месяца назад

      @@nikoo28please check it out
      class Solution {
      public int longestConsecutive(int[] nums) {
      int n = nums.length;
      int left=1;
      int right =1;
      int ans=nums[0];
      for(int i=0;i

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

    Hey... can we solve similar kind of question , finding maximum sum of subarray in given array. It usually solved using kadane's algorithm, but can we use this approach?
    Any way superb explanation ....

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

      give me a link to the question.

  • @abdulgaffarabdulmalik4333
    @abdulgaffarabdulmalik4333 10 месяцев назад +8

    My question is, why does it work?

    • @nikoo28
      @nikoo28  9 месяцев назад +2

      please elaborate...

    • @billyfigueroa1617
      @billyfigueroa1617 5 месяцев назад +1

      😂

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

      answer to ur question is if u observe carefully traversing from left and right indirectly we are calculating product of all sub array and each time storing max subbarray product

  • @telugustatuscreator8327
    @telugustatuscreator8327 5 месяцев назад

    How are you getting ideas like this?

    • @nikoo28
      @nikoo28  4 месяца назад

      practice, practice, practice and a lot of practice my friend :)

  • @meme.ada...1367
    @meme.ada...1367 Месяц назад +1

    wrong hai solution
    leetcode per 190 testcase fail ho raha

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

      they have updated the test cases.

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

      thanks for letting me know...I will update the code accordingly

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

    Failed or -1, 0,-3

    • @jiddu99
      @jiddu99 Месяц назад +1

      How ? It passed i got 0

    • @nikoo28
      @nikoo28  29 дней назад

      yes, it will pass...and you will get 0

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

    Adios nikhil

  • @user-ph5ek8tg5l
    @user-ph5ek8tg5l Месяц назад

    Code Failed for nums =[0, 10, 10, 10, 10, 10, 10, 10, 10, 10, -10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0]
    Your code is also failing on LeetCode. This test case seems to be added recently. Due to overflow the answer is coming wrong. Even though leetcode has said the final answer is within the int range but the intermediate values in calculation are overflowing even the long range.
    Below code changes will fix the issue.
    long leftProduct = 1;
    long rightProduct = 1;
    long ans = nums[0];
    leftProduct = (leftProduct == 0 || leftProduct < Integer.MIN_VALUE) ? 1 : leftProduct;
    rightProduct = (rightProduct == 0 || rightProduct < Integer.MIN_VALUE) ? 1 : rightProduct;
    return (int) ans;

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

      yes, that seems to be a newly added test case. I will update the code accordingly. Thanks for your contribution 😄

  • @robertnant1264
    @robertnant1264 4 месяца назад

    Hi! First of all thank you for the video. I'm having a hard time understanding why we have to calculate the product going from the left and also going from the right side of the array. Why is it that a traversal from start of array to its end does not work?
    Thank you in advance

    • @nikoo28
      @nikoo28  4 месяца назад

      did you follow the explanation of the solution, or just looking at the code?

  • @user-mk7qi6gc2m
    @user-mk7qi6gc2m Месяц назад +1

    You wont pass 1 test case, for that use double instead of int

    • @nikoo28
      @nikoo28  29 дней назад +1

      i fixed the code in link

  • @shivdeepbisurkar6526
    @shivdeepbisurkar6526 10 месяцев назад +1

    Hi, awesome explanation but it's failing for test case
    nums =[0, 10, 10, 10, 10, 10, 10, 10, 10, 10, -10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0]
    output=1981284352 using above logic.
    Expected =1000000000 (as per leetcode)

    • @nikoo28
      @nikoo28  9 месяцев назад +1

      my code passed on leetcode, did you check the one in the video description on github?

    • @user-ph5ek8tg5l
      @user-ph5ek8tg5l Месяц назад

      @@nikoo28 Your code is also failing on LeetCode. This test case seems to be added recently. Due to overflow the answer is coming wrong. Even though leetcode has said the final answer is within the int range but the intermediate values in calculation are overflowing even the long range.

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

      @@user-ph5ek8tg5l Did you resolve with any approch

  • @user-dg4vv5ru5h
    @user-dg4vv5ru5h 8 месяцев назад

    What if all elements are zero. Then it will fail?

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

      It won’t fail. The answer will be 0

  • @user-dg4vv5ru5h
    @user-dg4vv5ru5h 8 месяцев назад

    What if all elements are zero. Then it will fail?

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

      It will not fail