Maximum Sum Circular Subarray - Leetcode 918 - Python

Sdílet
Vložit
  • čas přidán 27. 07. 2024
  • 🚀 neetcode.io/ - A better way to prepare for Coding Interviews
    🥷 Discord: / discord
    🐦 Twitter: / neetcode1
    🐮 Support the channel: / neetcode
    ⭐ BLIND-75 PLAYLIST: • Two Sum - Leetcode 1 -...
    💡 DYNAMIC PROGRAMMING PLAYLIST: • House Robber - Leetco...
    Problem Link: leetcode.com/problems/maximum...
    0:00 - Read the problem
    1:10 - Kadane's Explanation
    5:00 - Circular Explanation
    14:00 - Coding Explanation
    leetcode 918
    #neetcode #leetcode #python

Komentáře • 44

  • @user-zs1em2hm3p
    @user-zs1em2hm3p Před rokem +44

    The last edge case is not the most confusing part, I find it pretty simple to understand.
    What is confusing, is intuition to think about the min subarray.

    • @yichenyao5927
      @yichenyao5927 Před rokem +1

      same here, I was sitting there thinking about all possible ways to do this but I can't, until I find this hint about the min subarray. wish I could be smarter at the interview 🥲

    • @CST1992
      @CST1992 Před 3 měsíci

      Yeah, the total, globalMax and globalMin part confused me.

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

      i like to imagine it like an obstacle,
      if a maximum sum subarray exists in a circular formation, i.e. the left and right ends of the array, then the obstacle in the middle will be the minimum sum subarray, so taking the total - global min, we get the circular portion which is the globalmax

    • @jasonwang3690
      @jasonwang3690 Před 6 dny

      not worth learning it at all

  • @hamzasayyid8152
    @hamzasayyid8152 Před rokem +27

    explanation is ok. I feel the part I lack understanding the most is realizing the minimum sum subarray being used. Might be useful to explain why that could be a solution or why it works, rather than just telling us it's the answer

    • @ZeonLP
      @ZeonLP Před rokem +6

      First of all, either the maximum sum subarray does not wrap around or it does. Suppose it does wrap around. Find the maximum subarray sum starting from i > 1 and ending at n - 1 inclusive (last item of the array). This will definitely be part of our solution. Now since we assumed the optimal solution includes wrapping around, we want to extend it from index 0 up to some index j > 0. Now suppose the minimum subarray was [k,l]. We want to show that i = l + 1 and j = k - 1. Because of minimality, we know that the sum of the surrounding elements 0, ..., k - 1 and l + 1, ..., n - 1 needs to be maximal. This sum must also be positive, otherwise we could have extended the minimum subarray. So we can conclude that the maximum circular subarray in this case will be [0, k-1] union [l+1, n-1].
      Edit: We also need to prove that the subarray [0, k-1] union [l+1, n-1] sum is larger than any smaller circular subarray sum within that area. Call the [0, k-1] union [l+1, n-1] subarray sum S and the smaller subarray one s. Suppose s > S. Then that would mean that at least on one side of [k,l] there are contiguous elements whose sum is negative, and thus we could have extended the minimum subarray which is a contradiction since we assumed minimality.

    • @bezu6784
      @bezu6784 Před rokem +8

      A bit late but the way I thought of it is that minimum sum is an "obstacle" to the max sum, but since the array is circular, we can just walk around that obstacle. We can only walk around one obstacle though or else the subarray would no longer be contiguous, so that's why we're keeping track the biggest obstacle we need to avoid while compromising and tanking the smaller ones along the way (i.e for an array that contains the subarrays [-5,-10] and [-20], we can only walk around one of these obstacles, so we're keeping track of which one would hurt the sum the most (-20))

  • @laumatthew71
    @laumatthew71 Před rokem +12

    Amazing explanation as usual, thank you NeetCode !
    However, I have to say that the intuition of "total - global_min will give us the potential answer of the circular case" is really hard to come up with...

    • @Raymond-Wu
      @Raymond-Wu Před rokem +2

      Absolutely this! I tried for about an hour playing around with prefix sums, left + right pointers, dp, and other things

    • @sionkim5504
      @sionkim5504 Před rokem +1

      I felt the same thing, but Neetcode's solution has opened new pov.

    • @ary_21
      @ary_21 Před rokem +1

      @@Raymond-Wu
      i copied the function i wrote for maximum subarray sum , instead of passing nums={5,-3,5} into the function i passed v={5,-3,5,5,-3,5} (flattening a circular array)
      now the problem is it gives answer is 14 while actual answer is 10 and that is because if i am already including v[2] in my sub array i am not allowed to include v[5]
      if length of nums is x (then v.size() is 2x)
      if i am starting my subarray from index k
      then i am only allowed to expand my sliding window upto index such that 2k+1 isnt included
      or i can say they max length of my sliding window will be x at all times and this is how i prevented duplication

  • @GreenChiou
    @GreenChiou Před rokem

    Awesome and easy to understand, thank you.

  • @sunilpanchal1498
    @sunilpanchal1498 Před rokem +8

    As always super explanation 🙂

  • @himanshisharma7116
    @himanshisharma7116 Před rokem

    You are awesome..👏i just love the way how you explains the every logic in an crystal clear format.. just a big fan of yourself.. need an autograph 😅shiiiiiiii🤪

  • @jessanraj9086
    @jessanraj9086 Před rokem +2

    Your consistency is impressive brother

  • @ouchlock
    @ouchlock Před rokem

    Thanks for your work. Awesome videos, eloquent explanations, really helpful!
    I chose to compare total to min. If they are same then return max. Seems OK, LeetCode accepted it as well. What do you think about this way of processing edge case of all negative numbers?
    Rust code:
    if total == min {
    max
    } else {
    max.max(total - min)
    }

  • @Kayander1
    @Kayander1 Před rokem

    Great explanation!

  • @piyusharyaprakash4365

    I love your explanations. Just one doubt how do you come up with those solutions, like the workaround for the circular array is total - globalMin. How did you figure that out ?

  • @user-mj9ez5yk5i
    @user-mj9ez5yk5i Před 8 měsíci

    At some point in the starting of this video, you mentioned we want to be greedy for this problem, I don't think this is a greedy pattern. It more of look like DP approach where at each point or indexes you want to figure out what's the max sum I can achieve from this sub array. You are really breaking down the arrays to subarrays and trying to figure out the max sum can be achieve at particular index.

  • @robr4501
    @robr4501 Před rokem +3

    I don't quiet get the part,total - global min, how is that going to determine the max for circular array? how do i know if that included the circular case?

    • @Kamalesh.2207
      @Kamalesh.2207 Před měsícem +2

      Hey , First you need to consider 2 cases :
      1. MaxSumSubarray of the non-circular array.
      2. MaxSumSubarray of the circular array.
      3. Ans is the max of 1 and 2 .
      First is straight forward apply - Kadanes
      Second, is little tricky.
      MaxSumSubarray of circular array = Sum of the entire array - (MinSumSubarray) .
      How ? Imagine the minimum sum subarray is somewhere in the middle of your array. If the eliminate this from the total sum of the array we get the remaining sum.
      To find MinSumSubarray : -(Kadane’s algorithm on the inverted array) . If some subarray is maximum in the inverted array then it is the minimum in the original array. Hope this helps. Took me a lot of time to understand the intuition. Hope this helps. :)

    • @anusree8707
      @anusree8707 Před 22 dny

      @@Kamalesh.2207 understood this well now

  • @CostaKazistov
    @CostaKazistov Před rokem

    NeetCode has gotten so good at this now, that I have to slow down playback speed to in order to follow his logic.

  • @saikatrakshit3286
    @saikatrakshit3286 Před rokem

    Please make a video on Leetcode " 659. Split Array into Consecutive Subsequences ". I face difficulties to solve this.

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

    good one

  • @mohit8299
    @mohit8299 Před 4 měsíci

    thanks

  • @eddiej204
    @eddiej204 Před rokem +2

    Why have another channel, Neetcode bro?

  • @loganjame
    @loganjame Před 8 měsíci +2

    can someone explain what will happen with [-5,3,-5]? This will fail in that

    • @JuliaC-mz8qy
      @JuliaC-mz8qy Před měsícem

      I don't think the algorithm fails this test case. I threw this test case into leetCode, the algorithm returns 3. Do you expect a different result?
      Before we hit the return statement, globMax = 3, globMin = -7, and total = -7.
      Because the global max is greater than 0, we return the max between [3] and [-7 - (-7)] = 0.
      So between choosing which is the max, 0 and 3, 3 gets selected.

  • @JuliaC-mz8qy
    @JuliaC-mz8qy Před měsícem

    If someone asked me this in an interview, id be screwed.

  • @MIRAZIB
    @MIRAZIB Před rokem

    Can any one help and suggest me, how do you guys come up with this kind of approaches.
    Yes I know kadane's algorithm, I've practiced with many other approaches and yet can't think of this kind of complex but simple intuition 😭😭. Frustrated 😩

    • @pushkarchaubey8300
      @pushkarchaubey8300 Před 4 měsíci

      try this approach bro
      c3=0
      for i in nums:
      if(i0):
      c=0
      else:
      ma=min(ma,c)
      c1=0
      ma1=nums[0]
      for i in range(len(nums)):
      c1+=nums[i]
      if(c1

  • @manishdangi5491
    @manishdangi5491 Před rokem

    finally i saw a solution properly explaining logic after 5-6 videos
    🙂

  • @pushkarchaubey8300
    @pushkarchaubey8300 Před 4 měsíci

    what you think about this solution
    c3=0
    for i in nums:
    if(i0):
    c=0
    else:
    ma=min(ma,c)
    c1=0
    ma1=nums[0]
    for i in range(len(nums)):
    c1+=nums[i]
    if(c1

  • @yunierperez2680
    @yunierperez2680 Před 5 měsíci

    Great explanation! Wondering how this channel is different from your other channel www.youtube.com/@NeetCode 🤔

  • @sumittogare
    @sumittogare Před rokem

    Neetcode are you Irish?.

  • @pavel.pavlov
    @pavel.pavlov Před 5 měsíci

    tooooo fast

  • @jasonwang3690
    @jasonwang3690 Před 6 dny

    it's nothing to do with coding at all.. it's IQ and math test. How is it going to help people learning coding at all?

    • @jasonwang3690
      @jasonwang3690 Před 6 dny

      If the candidate pass this question, the only thing that can show is that this candidate spend a lot of time learning and this candidate is patient. Nothing else can prove this candidate is good coder or not.

  • @dera_ng
    @dera_ng Před rokem +2

    Greedy algorithms 🥲... I wish I had studied computer science in College.

    • @NeetCodeIO
      @NeetCodeIO  Před rokem +8

      Fwiw most of this stuff I learned after college 😅