← All problems
#121EasyπŸ”’ Pattern ???

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 LeetCode
πŸ€” GUESS THE PATTERN+5 XP

Before 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

  1. buy = prices[0], best = 0.
  2. For each price p from day two:
    • If p < buy, slide the window: buy = p.
    • Otherwise best = max(best, p - buy).
  3. 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

TimeO(n)
SpaceO(1)

πŸ’» 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 best

Got it and submitted?

Mark it solved to earn XP and keep your streak alive.