# The Market Timer

> One buy, one sell - when do you make the most?

Canonical URL: <https://datadriven.io/problems/the_market_timer>

Domain: Python · Difficulty: medium · Seniority: L3

## Problem

Given a list of prices, return the maximum profit from a single buy then later sell, or 0 if none is profitable.

## Worked solution and explanation

### Why this problem exists in real interviews

This is a classic **single-pass optimization** problem. It tests whether candidates can track a running minimum and compute the best outcome without brute-forcing all pairs, which is the hallmark of greedy algorithm thinking.

---

### Break down the requirements

#### Step 1: Track the minimum price seen so far

As you scan left to right, maintain the lowest price encountered. This represents the best possible buy day up to this point.

#### Step 2: Compute profit at each step

For each day, the profit if selling today is `price - min_so_far`. Compare this against the best profit found so far.

#### Step 3: Return the maximum profit

If no positive profit is possible (prices only decrease), the result is 0.

---

### The solution

**Single-pass with running minimum**

```python
def max_profit(prices):
    if not prices:
        return 0
    min_price = prices[0]
    best_profit = 0
    for i in range(1, len(prices)):
        profit = prices[i] - min_price
        if profit > best_profit:
            best_profit = profit
        if prices[i] < min_price:
            min_price = prices[i]
    return best_profit
```

> **Time and Space Complexity**
>
> **Time:** O(n) with a single pass through the price list.
> 
> **Space:** O(1). Only two variables track state.

> **Interviewers Watch For**
>
> Do you immediately recognize that buying must happen before selling? This constraint means you scan left to right, updating the minimum as you go. Candidates who try to sort the array miss this temporal dependency.

> **Common Pitfall**
>
> Initializing `best_profit` to negative infinity instead of 0. The problem says to return 0 when no profit is possible, so starting at 0 handles that naturally.

---

## Common follow-up questions

- What if you could buy and sell multiple times? _(Tests the greedy approach: sum all positive consecutive differences.)_
- What if there was a cooldown period after selling? _(Tests dynamic programming with state transitions.)_
- What if you also had to return the buy and sell days? _(Tests tracking indices alongside the running min and max profit.)_

## Related

- [All practice problems](https://datadriven.io/problems)
- [Mock interview mode](https://datadriven.io/interview/the_market_timer)
- [Python Interview Questions](https://datadriven.io/python-interview-questions)
- [Data Engineering Interview Prep Guide](https://datadriven.io/data-engineer-interview-prep)
- [Daily Challenge](https://datadriven.io/daily)

---

Source: DataDriven (https://datadriven.io). 100% free data engineering interview prep. Live code execution against Postgres 16, Python 3.11, and Spark sandboxes. No paywall, no premium tier, no signup gate.