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.
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
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!
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!
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.
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.
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.
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.
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
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
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!
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
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.
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.
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.
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?
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.
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). ?
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 ;-)
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.
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
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?
Best Time to Buy and Sell a Stock 1: ua-cam.com/video/1pkOgXD63yU/v-deo.html
I definitely overthought this problem. Thanks for solution
Same here :) I thought everything possible to get the selling point.
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.
@@pgkrit Definitely. I saw dynamic programming, misread the problem and thought you could only buy the day after selling 😭
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
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!
Thanks i'm happy they are helpful :)
wow...I initially thought this would be complicated...Your explanation make it look easy
Brohhhh !!!
It really blows my mind how simple the solution is 🙌
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.
Yes, this is the part I didn't realize works every single time!
Hi, what do you mean by slope along the x axis? Slope definition is (y2 - y1) / (x2 - x1). This problem stinks :’( :’(
That's a valuable insight. It cleared my confusion about how this solution finally worked.
you helped me, thank you so much
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!
have you ?
Best Time to Buy and Sell Stock III & IV are really difficult , hope you can make a video for these questions too.
Thanks
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.
Thank you! I didn't need to watch the video, because of your comment!
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.
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.
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.
Thank you Bob Ross of the coding, Wish I can be as clear as you in interview one day
can you do video of buy and sell a stock 3 and 4 also ?
Yeah, I plan on doing those problems as well!
@@NeetCode Please ~~~~~
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
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
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!
this was a hell lot easier than what i actually thought it would be😅😅
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
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.
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.
Does anyone else feel like this question is easier than Best Time to Buy and Sell a Stock I
No
Only after hearing his understanding of the algorithm, not before that :p
No
Generating wrong result for below Input
Input:
prices = [7,1,5,3,6,4]
Output = 7
Expected = 5
Oh my god, this one was super easy when you visualize it.
Nice video!
BTW, the problem is updated now, can you make a video on that?
Clearly overthought this, only to find out it's even much easier than its 1st variant on Leetcode 😄. thank you!
Short and concise explanation! Thank you.
can we hold for longer than one day? is there such a question?
i think buying and selling in increments is equivalent to just holding it
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.
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?
Can you solve it by using dynamic programming? Thanks
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
thanks bro i definitely overthought this problem. Thank for solution
leetcode is pretty funny for making this a medium and Buy and Sell I an easy.
Well done man
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.
This one is simpler than the first version of this problem
my initial intuition think about this approach but i didn’t believe it is indeed the solution!
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)
Commenting because I want to help the channel, but not sure what to comment lol. Good job
Thanks!
Thank you so much!
@@NeetCode No need to thank me! I'm really grateful your videos exist so i'm just showing my appreciation.
hodl. 4:45 unless you're investing in DOGE coin
Btw I like your short and clear cut explanation..videos length is small too....thanks...😉
Great Explanation👏
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). ?
I don't understand why dynamic programming / recursion is not necessary here
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 ;-)
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.
This logic is so easy, compare to the solutions on leetcode. I am in awe rn
Fantastic explanation sir.Subscribed and shared
OMG The way you simplified...❤
Why dp requireddd??? This was the best???? Isn't?
"Only If it was this easy in real life" - Neetcode 2021
thnx
Wow, this is extremely simple
and there I was like a dumbass looking for a dp solution lmao
4:40 lol
Het @NeetCode, can you please prepare or link me to your solution to problem 123 Buy & Sell Stocks3
No matter what content you read, don't have a lot of emotion, what things would you say you would go to?
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
THANKS SIR !!
U a God
Intuition to the solution and actual solution aren't at the same difficulty I guess or I'm having an off day 😕
Excellent
Lol the question basically told us what to do! Same Day Sell and Buy
i did a 2d cache and added the diagonals, felt so dumb when i saw this vid xD
Please upload more videos. 👍
you are my hero
Please do 3 and 4 also
dogecoin 🚀 :D
The code is wrong but the explanation is great.
what do you mean it's wrong? o.0
Wait, you don't buy high and sell low???
The Question statement is sometimes meant to trick your brain from thinking the easiest solution.....that's when I come here 😊
Best Time to Buy and Sell a Stock III ?
Thanks bro....I tried doing everything...but now I can die in peace
Now it is Medium, not Easy.
I see the future 😋
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)))
legend
Cool...algo❤️
Bro i did think of this solution but i thought it was a brute force solution. Turned out i was just overthinking it 🙃
My reaction when I saw your solution:
WTF looooool
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?
He is none indian king
whhhhaaaaaaat
your code doesnt justify your explanation
So you can't buy at 1 and sell part at 5, and then buy again at 1 and sell at 3?
What if the input is 1234567
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
Thanks!
Impressive. Hope I can have your mindset on solving problems one day