Skip to the solution
EasyDSA9 min read

How do you find the best time to buy and sell a stock?

865 views

The problem

Question presented to candidate: "You are given a list of daily stock prices. You may buy one share on one day and sell it on a later day. Write a Python function that returns the maximum profit you can make, or 0 if no trade makes money."

What a strong answer should cover:

  • The order constraint: the buy day must come before the sell day, so max(prices) - min(prices) is wrong.
  • The one-pass idea: keep the cheapest price seen so far and the best profit so far; O(n) time, O(1) space.
  • Why it is correct: for each sell day the best buy is the minimum of the earlier prices.
  • Edge cases: empty list, one price, falling prices (answer 0).
  • Python details: float('inf') as the starting minimum, and why min(prices[:i]) inside the loop silently makes it O(nยฒ) (slicing copies).
  • The unlimited-trades follow-up: sum of all positive day-to-day differences.

Clarifying questions expected:

  • Exactly one transaction, or many?
  • Should a falling market return 0 or the smallest loss?

Code / implementation expected: Yes โ€” a single for loop over the list with two variables, in Python 3.

  • arrays
  • greedy

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

9 min read ยท 12 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonOne pass: cheapest price so far + best profit (7 inputs)
PythonBuy/sell days, brute force vs one pass, unlimited trades

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 12 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextEasy

How do you merge two sorted linked lists?

Continue