Best Time to Buy and Sell a Stock II - Leetcode 122 - Python

Sdílet
Vložit
  • čas přidán 27. 07. 2024
  • 🚀 neetcode.io/ - A better way to prepare for Coding Interviews
    🐦 Twitter: / neetcode1
    🥷 Discord: / discord
    🐮 Support the channel: / neetcode
    💡 CODING SOLUTIONS: • Coding Interview Solut...
    💡 DYNAMIC PROGRAMMING PLAYLIST: • House Robber - Leetco...
    🌲 TREE PLAYLIST: • Invert Binary Tree - D...
    💡 GRAPH PLAYLIST: • Course Schedule - Grap...
    💡 BACKTRACKING PLAYLIST: • Word Search - Backtrac...
    💡 LINKED LIST PLAYLIST: • Reverse Linked List - ...
    Problem Link: leetcode.com/problems/best-ti...
    0:00 - Read the problem
    1:10 - Drawing Explanation
    4:52 - Coding Explanation
    leetcode 122
    This question was identified as an interview question from here: github.com/xizhengszhang/Leet...
    #sliding #window #python
    Disclosure: Some of the links above may be affiliate links, from which I may earn a small commission.
  • Věda a technologie

Komentáře • 107

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

    Best Time to Buy and Sell a Stock 1: czcams.com/video/1pkOgXD63yU/video.html

  • @rothenbergt
    @rothenbergt Před 2 lety +86

    I definitely overthought this problem. Thanks for solution

    • @agnishwarbagchi4935
      @agnishwarbagchi4935 Před rokem +3

      Same here :) I thought everything possible to get the selling point.

    • @pgkrit
      @pgkrit Před 4 měsíci +1

      I saw dynamic programming in the topics and immediately started to *WAY* overthink this for almost an hour. Then I realized how simple the solution was and came up with it in 30 seconds.

    • @Ibbysz
      @Ibbysz Před 3 měsíci +5

      @@pgkrit Definitely. I saw dynamic programming, misread the problem and thought you could only buy the day after selling 😭

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

      same here, i thought we should find max profit for a share and then buy on next day. in reality they bought everyday and sold only when in profit next day

  • @swathiayas
    @swathiayas Před 2 lety +56

    I love the way you explain! Even when I'm struggling, I feel if there is a video by you, then I will definitely understand it. Thank you for making such good videos!

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

      Thanks i'm happy they are helpful :)

  • @pa114able
    @pa114able Před 3 lety +27

    wow...I initially thought this would be complicated...Your explanation make it look easy

  • @bhanuprasadpatibandla8263
    @bhanuprasadpatibandla8263 Před 2 lety +27

    The key point is that buying and selling will always be equal to or higher than holding between any rising slope formed along the x axis.

    • @videowatcher4852
      @videowatcher4852 Před rokem +4

      Yes, this is the part I didn't realize works every single time!

    • @CantBeTamed53
      @CantBeTamed53 Před 8 měsíci

      Hi, what do you mean by slope along the x axis? Slope definition is (y2 - y1) / (x2 - x1). This problem stinks :’( :’(

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

      That's a valuable insight. It cleared my confusion about how this solution finally worked.

  • @christophershibles383
    @christophershibles383 Před 2 lety +6

    You're so good at explaining things that I got a few minutes in and realized exactly what to do. I am so glad to have found your channel because even if you don't have a video for a specific problem, your explanation and walk throughs on similar problems were still helpful enough that I was able to complete a hard level problem on my first try and it was pretty efficient. If I ever start applying for jobs and get one after passing a tech interview, you can bet I'd send a more appropriate thanks!

  • @hwp438
    @hwp438 Před rokem +7

    Brohhhh !!!
    It really blows my mind how simple the solution is 🙌

  • @karthik829
    @karthik829 Před 2 lety +5

    Thank you Bob Ross of the coding, Wish I can be as clear as you in interview one day

  • @b9944236
    @b9944236 Před rokem +5

    Best Time to Buy and Sell Stock III & IV are really difficult , hope you can make a video for these questions too.
    Thanks

  • @programming3043
    @programming3043 Před 2 lety +34

    Recap:
    1. Classic sliding window problem
    2. Take a window of size 2 and compare the values.
    3. If the later value is greater that means a profit.
    4. Store the profit in your result (accumulate the result).
    5. If the later value is smaller that means a loss. So, we won't do that trade. Just move 1 index ahead.
    6. Repeat step 3 till the end of the array/list.
    7. Return the result.

    • @naifalkhunaizi7847
      @naifalkhunaizi7847 Před 6 měsíci +1

      Thank you! I didn't need to watch the video, because of your comment!

  • @username_0_0
    @username_0_0 Před 2 lety +1

    Short and concise explanation! Thank you.

  • @devdev19
    @devdev19 Před 2 lety +31

    Does anyone else feel like this question is easier than Best Time to Buy and Sell a Stock I

  • @zacharyarden3167
    @zacharyarden3167 Před rokem

    video really highlighted the value of drawing out the problem, was stuck for 30 minutes with no code, could only come up with a silly o(n2) solution, but when drawn out on a graph the solution is extremely obvious

  • @metin4yt
    @metin4yt Před rokem +4

    Even though the solution passes on leetcode, it does not align with intuition. The only reason this is working is due to the fact that you can sell and buy on the same day. If you wouldn't be allowed to do that, then the solution won't work. For example on [1,2,3] it will give 1 instead of 2.
    I left this comment due to the fact that a lot of people are saying that it feels harder than the solution. And that's for good reasons.

    • @nikhil_a01
      @nikhil_a01 Před rokem +1

      You have a point. But even if the problem didn't allow you to sell and buy on the same day, there's no functional difference between that and just holding the stock.
      I the prices are [1,2,3] and I tell you I got a profit of 2, it's impossible for you to tell whether I bought on day 1 and sold on day 3. Or if I bought on day 1, sold on day 2, bought again on day 2, and sold on day 3.
      Also, this is not the only solution. There's a solution that aligns more with the intuition but it's not as elegant. One disadvantage of watching most CZcamsrs, including NeetCode, is that they only cover a single approach.

    • @ihsannuruliman4005
      @ihsannuruliman4005 Před 11 měsíci +1

      This is incorrect.
      "You can buy it then immediately sell it on the same day."
      Honestly this statement is confusing. A better way is this:
      "You can do buy and sell on the same day."
      So this approach also works:
      [1,5,8]
      buy 1, sell 5. profit = 4. buy 5, sell 8. profit = 4 + 3 = 7.
      Instead of:
      buy 1, sell 8.

  • @prasantharavindramesh1078

    Fantastic explanation sir.Subscribed and shared

  • @VictorGarcia-si8wy
    @VictorGarcia-si8wy Před 2 lety +1

    Oh my god, this one was super easy when you visualize it.

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

    Clearly overthought this, only to find out it's even much easier than its 1st variant on Leetcode 😄. thank you!

  • @snehel1586
    @snehel1586 Před 2 lety +2

    this was a hell lot easier than what i actually thought it would be😅😅

  • @halahmilksheikh
    @halahmilksheikh Před 2 lety

    Why is it that if you add a cooldown to this problem, it becomes so much more complex? Like for leetcode 309 in your video, it's a top down dynamic programming question. The question is almost the same except for the cooldown but requires way more thinking and code.

  • @NguyenTuan-ek1pv
    @NguyenTuan-ek1pv Před 2 lety +1

    Well done man

  • @culunman1198
    @culunman1198 Před 2 lety

    my initial intuition think about this approach but i didn’t believe it is indeed the solution!

  • @eminence_Shadow
    @eminence_Shadow Před rokem

    Btw I like your short and clear cut explanation..videos length is small too....thanks...😉

  • @MinhNguyen-lz1pg
    @MinhNguyen-lz1pg Před rokem +3

    Really wish the question mentioned "total profit", the max profit can be miss-leading into "Best Time to Buy and Sell Stock I". Good explanation tho haha

  • @gangstersofsona8486
    @gangstersofsona8486 Před rokem +1

    Nice video!
    BTW, the problem is updated now, can you make a video on that?

  • @yashdeshpande1886
    @yashdeshpande1886 Před 6 měsíci

    Great Explanation👏

  • @samlinus836
    @samlinus836 Před rokem

    OMG The way you simplified...❤

  • @vugiakhanhk17hl23
    @vugiakhanhk17hl23 Před dnem

    thanks bro i definitely overthought this problem. Thank for solution

  • @nikhildinesan5259
    @nikhildinesan5259 Před 3 lety +7

    can you do video of buy and sell a stock 3 and 4 also ?

    • @NeetCode
      @NeetCode  Před 3 lety +3

      Yeah, I plan on doing those problems as well!

    • @b9944236
      @b9944236 Před rokem

      ​@@NeetCode Please ~~~~~

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

    Commenting because I want to help the channel, but not sure what to comment lol. Good job

  • @Fasttrackhunny12345
    @Fasttrackhunny12345 Před 2 lety

    Het @NeetCode, can you please prepare or link me to your solution to problem 123 Buy & Sell Stocks3

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

    This is how I solved the problem too, but was thinking the solution would break for some hidden test cases because it was categorized as MEDIUM but it didn't. Also the problem topic says Dynamic Programming in it. How can we solve this using dynamic programming? Any thoughts on that?

  • @Bassface793
    @Bassface793 Před 9 měsíci

    This logic is so easy, compare to the solutions on leetcode. I am in awe rn

  • @user-ts5py4cn3b
    @user-ts5py4cn3b Před 4 měsíci +2

    At first I thought this problem was more complicated. Surely you can't just always sell the next day if it goes higher, right? But yes that really is the solution. What if it goes up a little then down a little then up a lot though, might it be better to hold all the way from the first to the last? No, because we can freely sell and buy on any day with no fee, so we sell before it goes down a bit, then buy again once its down, then sell again once it goes even higher. But then what if it continues to increase, shouldn't you hold then? Again, no because we can just buy again right after we sell, so there's no difference between holding through 2 increasing days and selling and buying in-between

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

      A great summary. I wonder if it's the traditional investment wisdom of 'buy low and sell high after a long period of time' that causes this mental conflict to begin with. Maximising profit every local opportunity isn't as obvious as you think it would be. Seemed like a DP problem initially, but with no transaction cost or cooldown requirements, considering sub-problems is wholly unnecessary. Hope your leetcoding and interviews go well!

  • @Shanky_17
    @Shanky_17 Před 3 lety

    THANKS SIR !!

  • @Cloud-577
    @Cloud-577 Před 2 lety +2

    can we hold for longer than one day? is there such a question?

    • @azariafowler6782
      @azariafowler6782 Před 2 lety +4

      i think buying and selling in increments is equivalent to just holding it

  • @antonalekseyev9651
    @antonalekseyev9651 Před 8 měsíci

    What about applying your algorithm to the input array: [7, 1, 5, 3, 6, 100, 4] ?
    Buy on day 2 -> sell day 3 gives 4. Buy on day 5 -> sell on day 6 gives 94. Total 98.
    But in the same time if we buy on day 2 -> sell on day 6 gives 99.

    • @der_Echte
      @der_Echte Před 7 měsíci

      In his approach, he adds the difference between 3 and 6, as well as between 6 and 100. This implies that he doesn't buy the stock on day 4; rather, he simply adds the difference to the previous day. The misunderstanding lies in assuming he always buys when the condition is met, but in reality, he only adds the difference if it's positive.

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

    They've added a new constraint to this problem where they mandate that you sell on the next day i.e. you cannot hold more than one stock more than one day.
    e.g. you cannot buy on day 2 and sell on day 5.

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

    Can you solve it by using dynamic programming? Thanks

    • @agnesakne4409
      @agnesakne4409 Před rokem

      yes, leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/discuss/2561950/C%2B%2B-solution-with-early-termination-for-test-case-120

  • @hamoodhabibi7026
    @hamoodhabibi7026 Před rokem

    Lol the question basically told us what to do! Same Day Sell and Buy

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

    Wow, this is extremely simple

  • @subhashreebanik8131
    @subhashreebanik8131 Před 3 lety

    Please upload more videos. 👍

  • @btsforever7815
    @btsforever7815 Před 2 lety

    you are my hero

  • @raiyanahmed3534
    @raiyanahmed3534 Před 2 lety

    i did a 2d cache and added the diagonals, felt so dumb when i saw this vid xD

  • @csinfoplus3788
    @csinfoplus3788 Před rokem

    Excellent

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

    This one is simpler than the first version of this problem

  • @chenyangwang7232
    @chenyangwang7232 Před rokem

    Thanks!

    • @chenyangwang7232
      @chenyangwang7232 Před rokem

      Impressive. Hope I can have your mindset on solving problems one day

  • @yadavankit
    @yadavankit Před 7 měsíci

    this looks easier than #121 why LC categorized it as medium? started to doubt myself after solving in 2 min with runtime beating 100% users😀
    I think the problem statement is missing "in minimum number of transactions", they might have realized it but kept it because some youtubers made solutions already ;-)

  • @gagankaushik556
    @gagankaushik556 Před 11 dny

    thnx

  • @aayushgupta6914
    @aayushgupta6914 Před rokem

    Please do 3 and 4 also

  • @mohdshaheemidrisi8719
    @mohdshaheemidrisi8719 Před 2 lety +1

    hodl. 4:45 unless you're investing in DOGE coin

  • @priyanshmathur3010
    @priyanshmathur3010 Před rokem

    The Question statement is sometimes meant to trick your brain from thinking the easiest solution.....that's when I come here 😊

  • @ceb-rj4qw
    @ceb-rj4qw Před 2 lety

    legend

  • @eminence_Shadow
    @eminence_Shadow Před rokem

    Thanks bro....I tried doing everything...but now I can die in peace

  • @BAMBAMBAMBAMBAMval
    @BAMBAMBAMBAMBAMval Před rokem

    I guess youre only allowed to hold 1 stock at a time, otherwise you could buy on 1, buy on 5 and buy on 3 and sell all 3 on 6, giving you a profit of 9

  • @agnesakne4409
    @agnesakne4409 Před rokem +1

    I don't understand why dynamic programming / recursion is not necessary here

  • @SiddharthPanda_infinity_crew

    "Only If it was this easy in real life" - Neetcode 2021

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

    U a God

  • @bryce.ferenczi
    @bryce.ferenczi Před rokem

    Wait, you don't buy high and sell low???

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

    4:40 lol

  • @jasonswift7468
    @jasonswift7468 Před rokem

    No matter what content you read, don't have a lot of emotion, what things would you say you would go to?

  • @Shubhakar97
    @Shubhakar97 Před rokem

    Bro i did think of this solution but i thought it was a brute force solution. Turned out i was just overthinking it 🙃

  • @AllanBenDewey
    @AllanBenDewey Před rokem

    I see the future 😋

  • @jean4j_
    @jean4j_ Před rokem

    My reaction when I saw your solution:
    WTF looooool

  • @nikhilg251
    @nikhilg251 Před 6 dny

    Generating wrong result for below Input
    Input:
    prices = [7,1,5,3,6,4]
    Output = 7
    Expected = 5

  • @DK-ng3br
    @DK-ng3br Před rokem

    Now it is Medium, not Easy.

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

    Intuition to the solution and actual solution aren't at the same difficulty I guess or I'm having an off day 😕

  • @jongxina3595
    @jongxina3595 Před rokem

    and there I was like a dumbass looking for a dp solution lmao

  • @vickyroy3595
    @vickyroy3595 Před 7 měsíci +1

    Why dp requireddd??? This was the best???? Isn't?

  • @mollaabbas4695
    @mollaabbas4695 Před 2 lety

    Cool...algo❤️

  • @ankitkaushal442
    @ankitkaushal442 Před 3 lety +3

    dogecoin 🚀 :D

  • @emmanuelcestoni4105
    @emmanuelcestoni4105 Před rokem

    The code is wrong but the explanation is great.

  • @numberonep5404
    @numberonep5404 Před 2 lety

    in one line xd : def maxProfit(self, prices: List[int]) -> int: sum(max(prices[i]-prices[i-1], 0) for i in range(1, len(prices)))

  • @deepakkadali2563
    @deepakkadali2563 Před 7 měsíci

    Best Time to Buy and Sell a Stock III ?

  • @alphaOrderly
    @alphaOrderly Před 7 měsíci

    He is none indian king

  • @owenwu7995
    @owenwu7995 Před rokem

    So you can't buy at 1 and sell part at 5, and then buy again at 1 and sell at 3?

  • @popop72276
    @popop72276 Před 2 lety

    whhhhaaaaaaat

  • @user-ts5py4cn3b
    @user-ts5py4cn3b Před 4 měsíci

    OK but in your explanation you didn't really explain exactly how we choose when to buy and sell. It's not as simple as just looking at the next day and selling if it went up, because what if it goes up more? What if it goes down a bit then goes up even more?

  • @yashtarwe6878
    @yashtarwe6878 Před rokem

    your code doesnt justify your explanation

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

    using local minimum approach:
    class Solution(object):
    def maxProfit(self, prices):
    """
    :type prices: List[int]
    :rtype: int
    """
    profitsum = []
    minvv = float('inf')
    for i in range(len(prices)):
    minvv = min(minvv, prices[i])
    temp = len(profitsum)
    print temp
    if prices[i] - minvv > 0:
    profitsum.append(prices[i] - minvv)
    if len(profitsum) > temp:
    minvv = prices[i]
    return sum(profitsum)

  • @prasadm3614
    @prasadm3614 Před rokem +1

    What if the input is 1234567

    • @user-px8ez7qp5c
      @user-px8ez7qp5c Před 18 dny

      You can buy and sell on the same day. So in this case you would just buy and sell every day. Total profit is gonna be 6

  • @Atm34
    @Atm34 Před 2 lety +1

    Thanks!

    • @NeetCode
      @NeetCode  Před 2 lety +2

      Thank you so much!

    • @Atm34
      @Atm34 Před 2 lety +1

      @@NeetCode No need to thank me! I'm really grateful your videos exist so i'm just showing my appreciation.