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 whymin(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.