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

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

КОМЕНТАРІ • 112

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

    Best Time to Buy and Sell a Stock 1: ua-cam.com/video/1pkOgXD63yU/v-deo.html

  • @rothenbergt
    @rothenbergt 3 роки тому +104

    I definitely overthought this problem. Thanks for solution

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

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

    • @pgkrit
      @pgkrit 6 місяців тому +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 5 місяців тому +5

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

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

      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 3 роки тому +60

    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  3 роки тому +7

      Thanks i'm happy they are helpful :)

  • @pa114able
    @pa114able 3 роки тому +27

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

  • @hwp438
    @hwp438 Рік тому +7

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

  • @bhanuprasadpatibandla8263
    @bhanuprasadpatibandla8263 2 роки тому +29

    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 Рік тому +4

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

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

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

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

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

    • @Jompossivel
      @Jompossivel 16 днів тому

      you helped me, thank you so much

  • @christophershibles383
    @christophershibles383 2 роки тому +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!

  • @b9944236
    @b9944236 Рік тому +7

    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 2 роки тому +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 8 місяців тому +1

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

  • @metin4yt
    @metin4yt 2 роки тому +5

    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 Рік тому +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 UA-camrs, including NeetCode, is that they only cover a single approach.

    • @ihsannuruliman4005
      @ihsannuruliman4005 Рік тому +2

      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.

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

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

  • @nikhildinesan5259
    @nikhildinesan5259 3 роки тому +7

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

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

      Yeah, I plan on doing those problems as well!

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

      ​@@NeetCode Please ~~~~~

  • @MinhNguyen-lz1pg
    @MinhNguyen-lz1pg 2 роки тому +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

  • @user-ts5py4cn3b
    @user-ts5py4cn3b 6 місяців тому +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 5 місяців тому

      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!

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

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

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

    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

  • @antonalekseyev9651
    @antonalekseyev9651 9 місяців тому

    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 9 місяців тому

      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.

  • @devdev19
    @devdev19 2 роки тому +32

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

  • @nikhilg251
    @nikhilg251 Місяць тому +1

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

  • @VictorGarcia-si8wy
    @VictorGarcia-si8wy 2 роки тому +1

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

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

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

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

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

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

    Short and concise explanation! Thank you.

  • @Cloud-577
    @Cloud-577 3 роки тому +2

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

    • @azariafowler6782
      @azariafowler6782 2 роки тому +5

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

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

    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.

  • @avinashsorab5026
    @avinashsorab5026 7 місяців тому

    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?

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

    Can you solve it by using dynamic programming? Thanks

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

      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

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

    thanks bro i definitely overthought this problem. Thank for solution

  • @harshitgupta6856
    @harshitgupta6856 2 дні тому

    leetcode is pretty funny for making this a medium and Buy and Sell I an easy.

  • @NguyenTuan-ek1pv
    @NguyenTuan-ek1pv 2 роки тому +1

    Well done man

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

    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.

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

    This one is simpler than the first version of this problem

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

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

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

    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)

  • @chethanbhaskar9643
    @chethanbhaskar9643 7 місяців тому

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

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

    Thanks!

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

      Thank you so much!

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

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

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

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

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

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

  • @yashdeshpande1886
    @yashdeshpande1886 8 місяців тому

    Great Explanation👏

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

    Its so simple and elegant, but why is this problem being categorized as 'Medium', while this problem can simply be solved without knowing the concept of two pointers (or sliding window). ?

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

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

  • @yadavankit
    @yadavankit 9 місяців тому

    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 ;-)

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

    can anyone justify this for above solution :
    Input: prices = [1,2,3,4,5]
    Output: 4
    Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
    Total profit is 4.

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

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

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

    Fantastic explanation sir.Subscribed and shared

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

    OMG The way you simplified...❤

  • @vickyroy3595
    @vickyroy3595 9 місяців тому +1

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

  • @SiddharthPanda_infinity_crew
    @SiddharthPanda_infinity_crew 7 місяців тому

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

  • @gagankaushik556
    @gagankaushik556 2 місяці тому

    thnx

  • @КостяМос-я5о
    @КостяМос-я5о 9 місяців тому

    Wow, this is extremely simple

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

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

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

    4:40 lol

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

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

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

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

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

    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

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

    THANKS SIR !!

  • @edwardteach2
    @edwardteach2 4 місяці тому

    U a God

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

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

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

    Excellent

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

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

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

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

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

    Please upload more videos. 👍

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

    you are my hero

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

    Please do 3 and 4 also

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

    dogecoin 🚀 :D

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

    The code is wrong but the explanation is great.

  • @bryce.ferenczi
    @bryce.ferenczi 2 роки тому

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

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

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

  • @deepakkadali2563
    @deepakkadali2563 9 місяців тому

    Best Time to Buy and Sell a Stock III ?

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

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

  • @DK-ng3br
    @DK-ng3br Рік тому

    Now it is Medium, not Easy.

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

    I see the future 😋

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

    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)))

  • @ceb-rj4qw
    @ceb-rj4qw 2 роки тому

    legend

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

    Cool...algo❤️

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

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

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

    My reaction when I saw your solution:
    WTF looooool

  • @user-ts5py4cn3b
    @user-ts5py4cn3b 6 місяців тому

    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?

  • @alphaOrderly
    @alphaOrderly 9 місяців тому

    He is none indian king

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

    whhhhaaaaaaat

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

    your code doesnt justify your explanation

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

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

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

    What if the input is 1234567

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

    Thanks!

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

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