# Best Time to Buy and Sell Stock

[link](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/) · Easy · `array`, `running min`, `sliding window`

> "best pair i < j" → fix the right end and keep the best left end seen so far. Here the best left end is the running minimum, so one pass replaces the O(n^2) pair scan. Write it as a sliding window [l, r]: r always advances, l jumps to r when the window stops being worth keeping (a new low). That shape is the template for every sliding-window problem. The same trick shows up as "running max/min + answer at each step" and as Kadane's algorithm on the differences.

## Problem

> You are given an integer array `prices` where `prices[i]` is the price of NeetCoin on the `i`th day.
> You may choose a **single day to buy** one NeetCoin and choose a **different day in the future to sell** it.
> Return the **maximum profit** you can achieve. You may choose to not make any transactions, in which case the profit would be `0`.

**Example 1**
```
Input:  prices = [10,1,5,6,7,1]
Output: 6
```
Buy at `prices[1] = 1`, sell at `prices[4] = 7`, profit `7 - 1 = 6`.

**Example 2**
```
Input:  prices = [10,8,7,5,2]
Output: 0
```
Prices only go down, so no profitable transaction exists.

**Constraints**
- `1 <= len(prices) <= 100`
- `0 <= prices[i] <= 100`

## Thinking

- **Brute force idea:** try every pair `buy < sell` and keep the best `prices[sell] - prices[buy]`.
  $O(n^2)$ pairs.
- **Key insight:** fix the **sell** day. The best buy for it is simply the **cheapest price seen
  so far**. So one left-to-right pass keeps a running `min_price` and asks, at every day,
  "if I sold today, what would I make?" → $O(n)$ time, $O(1)$ space.
- **Same idea, other views:**
  - *Two pointers / sliding window:* `l` = buy day, `r` = sell day; whenever `prices[r] < prices[l]`,
    jump `l` to `r` (a new low makes every older buy day worse).
  - *Kadane:* the profit of buying on day `i` and selling on day `j` is the sum of the daily
    changes `prices[k+1] - prices[k]` in between, so the answer is the **max subarray sum** of
    the daily changes (or 0).
- **Edge cases to remember:** one day (no transaction possible → 0); strictly decreasing (→ 0,
  never negative); all equal (→ 0); the minimum appears **after** the maximum (`[7,1]` → 0, you
  can't sell before you buy); a new low later on that gives a bigger profit (`[3,8,1,9]` → 8);
  prices of 0.

## Solution

### Approach A — mine: running minimum, one pass
**Complexity:** Time $O(n)$ · Space $O(1)$

Already optimal in Big-O; it is the sliding window of Approach C with only the buy *price* kept instead of the buy *day*. For every day, update the cheapest buy price so far, then check the profit of selling today. Updating `buy` **before** computing the profit is fine: if today is the new low, the profit is `0`, which never beats `max_sell`. Two small things to tidy (not speed): the `if price - buy > 0` is redundant since `max(max_sell, 0)` changes nothing, and `return` on empty input gives `None` instead of `0` (unreachable here since `len(prices) >= 1`).

```python
def max_profit_mine(prices: list[int]) -> int:
    if not prices:
        return  # returns None, not 0 (unreachable: len(prices) >= 1)
    buy = prices[0]

    max_sell = 0

    for price in prices:
        buy = min(buy, price)

        if price - buy > 0:  # redundant: max() already ignores profits <= 0
            max_sell = max(max_sell, price - buy)
    return max_sell
```

### Approach B — brute force, every buy/sell pair
**Complexity:** Time $O(n^2)$ · Space $O(1)$

Directly the definition. Obviously correct, so the tests use it as the reference on random inputs. Fine at $n = 100$ (~5000 pairs), but it doesn't scale (LeetCode's own version has $n$ up to $10^5$).

```python
def max_profit_brute(prices: list[int]) -> int:
    best = 0
    for buy in range(len(prices)):
        for sell in range(buy + 1, len(prices)):  # O(n) inner loop for every buy day
            best = max(best, prices[sell] - prices[buy])
    return best
```

### Approach C — sliding window (two pointers) ✅ best practice
**Complexity:** Time $O(n)$ · Space $O(1)$

The version to remember. The window is `[l, r]`: `l` is the buy day, `r` the sell day. `r` always moves right; if `prices[r]` drops below the buy price, the window **shrinks** to start at `r` (a new low beats every older buy day), otherwise record the profit of the window. Same logic as A, but the explicit window carries over to the other sliding-window problems (#3, #424, #567).

```python
def max_profit_sliding_window(prices: list[int]) -> int:
    l, best = 0, 0
    for r in range(1, len(prices)):
        if prices[r] < prices[l]:  # new low: every later sale is better bought here
            l = r
        else:
            best = max(best, prices[r] - prices[l])
    return best
```

### Approach D — Kadane on the daily changes
**Complexity:** Time $O(n)$ · Space $O(1)$

Buying on day `i` and selling on day `j` earns `sum(prices[k+1] - prices[k] for k in i..j-1)`, so the answer is the maximum subarray sum of the daily changes. Worth knowing because it links this problem to Maximum Subarray (#53).

```python
def max_profit_kadane(prices: list[int]) -> int:
    best = cur = 0
    for prev, price in zip(prices, prices[1:]):
        cur = max(0, cur + price - prev)  # best profit for a sale today; reset if it goes negative
        best = max(best, cur)
    return best
```

### Approach E — Pythonic: `accumulate` the running minimum
**Complexity:** Time $O(n)$ · Space $O(1)$ (lazy iterators)

`accumulate(prices, min)` yields the cheapest price up to each day, so the answer is the largest gap between a price and the running min up to it. A one-liner; in an interview write C and mention this as the Pythonic form.

```python
from itertools import accumulate


def max_profit_accumulate(prices: list[int]) -> int:
    return max(p - low for p, low in zip(prices, accumulate(prices, min)))
```

## Scratch / Experiments

The constraints cap $n$ at 100, too small to show a difference, so the $O(n)$ approaches are timed at $n = 10^5$ (LeetCode's limit) and the brute force at $n = 2000$.

Measured (two runs): at $n = 10^5$, `accumulate` ~5.3–5.6 ms, mine ~6.1 ms, sliding window ~5.7–6.9 ms (noisy), Kadane ~6.8–7.6 ms. At $n = 2000$, brute force ~84–90 ms vs mine ~0.12 ms (~700×, and the gap grows linearly with $n$).

All four $O(n)$ versions are within run-to-run noise of each other, so pick by clarity, not speed. `accumulate` is consistently a little ahead because its loop runs in C. Kadane is consistently last: it builds `prices[1:]` and does two `max()` calls per step. None of this matters at $n = 100$.

```python
rng = random.Random(0)
prices = [rng.randint(0, 10_000) for _ in range(100_000)]
assert max_profit_mine(prices) == max_profit_sliding_window(prices) == max_profit_kadane(prices) == max_profit_accumulate(prices)
%timeit max_profit_mine(prices)
%timeit max_profit_sliding_window(prices)
%timeit max_profit_kadane(prices)
%timeit max_profit_accumulate(prices)

small = prices[:2000]
assert max_profit_brute(small) == max_profit_mine(small)
%timeit -n 1 -r 3 max_profit_brute(small)
%timeit max_profit_mine(small)
```

## Takeaways

- **Pattern:** **"best pair `i < j`" → fix the right end and keep the best left end seen so far.**
  Here the best left end is the running minimum, so one pass replaces the $O(n^2)$ pair scan.
  Write it as a **sliding window** `[l, r]`: `r` always advances, `l` jumps to `r` when the window
  stops being worth keeping (a new low). That shape is the template for every sliding-window problem.
  The same trick shows up as "running max/min + answer at each step" and as Kadane's algorithm on
  the differences.
- **Mistakes I made:** none in the algorithm, it's the optimal $O(n)$ / $O(1)$ solution. Polish:
  - The `if price - buy > 0` guard is unnecessary: `max_sell` starts at 0, so
    `max(max_sell, price - buy)` already ignores non-positive profits. Fewer branches, fewer bugs.
  - `return` with no value returns `None`; if you guard empty input, `return 0` to keep the
    return type `int`.
  - Name things for what they hold: `max_sell` is really the max **profit**, `buy` is the
    **min price** so far.
- **Related problems:** Best Time to Buy and Sell Stock II (#122, unlimited transactions: sum
  every positive daily change), III (#123, at most two transactions) and IV (#188, at most `k`,
  DP over states), with Cooldown (#309) and with Transaction Fee (#714) (state-machine DP);
  Maximum Subarray (#53, the Kadane view of this problem); Longest Substring Without Repeating
  Characters (#3, the next sliding-window problem).

---

From https://taosu.blog/notes/0121-best-time-to-buy-and-sell-stock
