Best Time to Buy and Sell Stock
Given a stock price for each day, pick one day to buy and a later day to sell for the biggest profit. If no profit is possible, the answer is 0.
Try it on LeetCodeBefore you peek at the solution: which pattern do you think this one uses?
Hints0/3
Optional. Open them one at a time if you're stuck.
π¬ Walkthrough video

Video coming soon
The video is still being edited. Meanwhile, read the explanation and the code.
π Explanation
Intuition
Picture a window whose left edge is the buy day and right edge is the sell day. The right edge always advances by one day.
If the price at the right edge is cheaper than the left edge, the old window is useless. Jump the left edge there, because buying lower is always better for every future day.
Steps
buy = prices[0],best = 0.- For each price
pfrom day two:- If
p < buy, slide the window:buy = p. - Otherwise
best = max(best, p - buy).
- If
- Return
best.
Dry run
prices = [7, 1, 5, 3, 6, 4]: buy drops to 1, then the best profit shows up at price 6, which is 5.
β±οΈ Complexity
π» Solution code
class Solution:
def maxProfit(self, prices: list[int]) -> int:
buy, best = prices[0], 0
for p in prices[1:]:
if p < buy:
buy = p
else:
best = max(best, p - buy)
return bestGot it and submitted?
Mark it solved to earn XP and keep your streak alive.