# The Trade Signal

> Buy low, sell high. Identify the ideal moment.

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

Domain: Python · Difficulty: easy · Seniority: L4

## Problem

Given a list of prices, find the max gain of a single buy-then-sell window. Return a 3-element list [gain, buy_day_index, sell_day_index]. If no profit is possible (gain <= 0), return [0, 0, 0]. Among multiple windows tied for max gain, return the one with the earliest buy index then earliest sell index.

## Worked solution and explanation

### Why this problem exists in real interviews

This tests the **maximum subarray / best-time-to-buy-and-sell** pattern. It probes whether a candidate can track a running minimum and compute the best profit in a single pass, avoiding the O(n^2) brute-force approach.

> **Trick to Solving**
>
> Track the minimum price seen so far. At each position, the best possible profit is `current_price - min_so_far`. Update the global maximum profit and the buy/sell indices as you go.

---

### Break down the requirements

#### Step 1: Track the minimum value and its index as you scan

The buy point is the lowest value seen before the current position.

#### Step 2: At each position, compute potential profit

If `values[i] - min_value` exceeds the current best, update the best profit and record both indices.

#### Step 3: Handle the no-profit case

If prices only decrease, the maximum profit is 0 (or negative, depending on the contract).

---

### The solution

**Single-pass min-tracking with profit calculation**

```python
def best_trade(values: list) -> tuple:
    if len(values) < 2:
        return (0, -1, -1)
    min_val = values[0]
    min_idx = 0
    best_profit = 0
    buy_idx = -1
    sell_idx = -1
    for i in range(1, len(values)):
        profit = values[i] - min_val
        if profit > best_profit:
            best_profit = profit
            buy_idx = min_idx
            sell_idx = i
        if values[i] < min_val:
            min_val = values[i]
            min_idx = i
    return (best_profit, buy_idx, sell_idx)
```

> **Time and Space Complexity**
>
> **Time:** O(n) for a single pass through the values.
> 
> **Space:** O(1). Only scalar tracking variables are used.

> **Interviewers Watch For**
>
> Returning indices alongside the profit value. Many candidates solve for the profit but forget to track where the buy and sell occur.

> **Common Pitfall**
>
> Checking all pairs with nested loops gives O(n^2). The single-pass approach with min tracking is optimal and expected.

---

## Common follow-up questions

- What if you could make multiple buy/sell transactions? _(Tests the greedy approach: sum all positive consecutive differences.)_
- What if there was a cooldown period between transactions? _(Tests dynamic programming with states for holding, cooldown, and ready.)_
- What if you could short-sell? _(Tests tracking max-so-far and computing max loss in addition to max gain.)_

## Related

- [All practice problems](https://datadriven.io/problems)
- [Mock interview mode](https://datadriven.io/interview/the_trade_signal)
- [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.