{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "6a8194d34c96",
   "metadata": {},
   "source": [
    "# Best Time to Buy and Sell Stock\n",
    "\n",
    "| Field      | Value                                   |\n",
    "|------------|-----------------------------------------|\n",
    "| Source     | [link](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/)  |\n",
    "| Difficulty | Easy                    |\n",
    "| Topics     | `array`, `running min`, `sliding window`                     |\n",
    "| Date       | 2026-10-19                              |\n",
    "| Status     | Solved                                  |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d1045ee19f66",
   "metadata": {},
   "source": [
    "## 1. Problem\n",
    "\n",
    "> You are given an integer array `prices` where `prices[i]` is the price of NeetCoin on the `i`th day.\n",
    "> You may choose a **single day to buy** one NeetCoin and choose a **different day in the future to sell** it.\n",
    "> Return the **maximum profit** you can achieve. You may choose to not make any transactions, in which case the profit would be `0`.\n",
    "\n",
    "**Example 1**\n",
    "```\n",
    "Input:  prices = [10,1,5,6,7,1]\n",
    "Output: 6\n",
    "```\n",
    "Buy at `prices[1] = 1`, sell at `prices[4] = 7`, profit `7 - 1 = 6`.\n",
    "\n",
    "**Example 2**\n",
    "```\n",
    "Input:  prices = [10,8,7,5,2]\n",
    "Output: 0\n",
    "```\n",
    "Prices only go down, so no profitable transaction exists.\n",
    "\n",
    "**Constraints**\n",
    "- `1 <= len(prices) <= 100`\n",
    "- `0 <= prices[i] <= 100`"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0a2fd258a6c3",
   "metadata": {},
   "source": [
    "## 2. Thinking\n",
    "\n",
    "- **Brute force idea:** try every pair `buy < sell` and keep the best `prices[sell] - prices[buy]`.\n",
    "  $O(n^2)$ pairs.\n",
    "- **Key insight:** fix the **sell** day. The best buy for it is simply the **cheapest price seen\n",
    "  so far**. So one left-to-right pass keeps a running `min_price` and asks, at every day,\n",
    "  \"if I sold today, what would I make?\" → $O(n)$ time, $O(1)$ space.\n",
    "- **Same idea, other views:**\n",
    "  - *Two pointers / sliding window:* `l` = buy day, `r` = sell day; whenever `prices[r] < prices[l]`,\n",
    "    jump `l` to `r` (a new low makes every older buy day worse).\n",
    "  - *Kadane:* the profit of buying on day `i` and selling on day `j` is the sum of the daily\n",
    "    changes `prices[k+1] - prices[k]` in between, so the answer is the **max subarray sum** of\n",
    "    the daily changes (or 0).\n",
    "- **Edge cases to remember:** one day (no transaction possible → 0); strictly decreasing (→ 0,\n",
    "  never negative); all equal (→ 0); the minimum appears **after** the maximum (`[7,1]` → 0, you\n",
    "  can't sell before you buy); a new low later on that gives a bigger profit (`[3,8,1,9]` → 8);\n",
    "  prices of 0."
   ]
  },
  {
   "cell_type": "code",
   "id": "815612ef4f72",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "# Setup: run this cell first. Lets you run pytest tests inside the notebook.\n",
    "try:\n",
    "    import ipytest\n",
    "except ImportError:  # Colab and other fresh kernels don't ship ipytest\n",
    "    %pip install -q ipytest\n",
    "    import ipytest\n",
    "import pytest\n",
    "\n",
    "ipytest.autoconfig()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7dff252d3f00",
   "metadata": {},
   "source": [
    "## 3. Solution\n",
    "\n",
    "### Approach A — mine: running minimum, one pass\n",
    "**Complexity:** Time $O(n)$ · Space $O(1)$\n",
    "\n",
    "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`)."
   ]
  },
  {
   "cell_type": "code",
   "id": "4f613d3f6fed",
   "metadata": {},
   "source": [
    "def max_profit_mine(prices: list[int]) -> int:\n",
    "    if not prices:\n",
    "        return  # returns None, not 0 (unreachable: len(prices) >= 1)\n",
    "    buy = prices[0]\n",
    "\n",
    "    max_sell = 0\n",
    "\n",
    "    for price in prices:\n",
    "        buy = min(buy, price)\n",
    "\n",
    "        if price - buy > 0:  # redundant: max() already ignores profits <= 0\n",
    "            max_sell = max(max_sell, price - buy)\n",
    "    return max_sell"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "3b25d219ffb1",
   "metadata": {},
   "source": [
    "### Approach B — brute force, every buy/sell pair\n",
    "**Complexity:** Time $O(n^2)$ · Space $O(1)$\n",
    "\n",
    "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$)."
   ]
  },
  {
   "cell_type": "code",
   "id": "8ae985f6f077",
   "metadata": {},
   "source": [
    "def max_profit_brute(prices: list[int]) -> int:\n",
    "    best = 0\n",
    "    for buy in range(len(prices)):\n",
    "        for sell in range(buy + 1, len(prices)):  # O(n) inner loop for every buy day\n",
    "            best = max(best, prices[sell] - prices[buy])\n",
    "    return best"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "a40626818cf2",
   "metadata": {},
   "source": [
    "### Approach C — sliding window (two pointers) ✅ best practice\n",
    "**Complexity:** Time $O(n)$ · Space $O(1)$\n",
    "\n",
    "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)."
   ]
  },
  {
   "cell_type": "code",
   "id": "e3966d67ffcd",
   "metadata": {},
   "source": [
    "def max_profit_sliding_window(prices: list[int]) -> int:\n",
    "    l, best = 0, 0\n",
    "    for r in range(1, len(prices)):\n",
    "        if prices[r] < prices[l]:  # new low: every later sale is better bought here\n",
    "            l = r\n",
    "        else:\n",
    "            best = max(best, prices[r] - prices[l])\n",
    "    return best"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "98c832222d70",
   "metadata": {},
   "source": [
    "### Approach D — Kadane on the daily changes\n",
    "**Complexity:** Time $O(n)$ · Space $O(1)$\n",
    "\n",
    "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)."
   ]
  },
  {
   "cell_type": "code",
   "id": "1e590e41489e",
   "metadata": {},
   "source": [
    "def max_profit_kadane(prices: list[int]) -> int:\n",
    "    best = cur = 0\n",
    "    for prev, price in zip(prices, prices[1:]):\n",
    "        cur = max(0, cur + price - prev)  # best profit for a sale today; reset if it goes negative\n",
    "        best = max(best, cur)\n",
    "    return best"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "dbd0ec93e7a5",
   "metadata": {},
   "source": [
    "### Approach E — Pythonic: `accumulate` the running minimum\n",
    "**Complexity:** Time $O(n)$ · Space $O(1)$ (lazy iterators)\n",
    "\n",
    "`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."
   ]
  },
  {
   "cell_type": "code",
   "id": "aa7f2aa7be6c",
   "metadata": {},
   "source": [
    "from itertools import accumulate\n",
    "\n",
    "\n",
    "def max_profit_accumulate(prices: list[int]) -> int:\n",
    "    return max(p - low for p, low in zip(prices, accumulate(prices, min)))"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "a2c007f5dfa1",
   "metadata": {},
   "source": [
    "## 4. Tests\n",
    "\n",
    "Every approach runs against every case; `test_random` compares all of them with the brute force on random arrays."
   ]
  },
  {
   "cell_type": "code",
   "id": "fcf157d05bba",
   "metadata": {},
   "source": [
    "%%ipytest -q\n",
    "import random\n",
    "\n",
    "FNS = [max_profit_mine, max_profit_brute, max_profit_sliding_window, max_profit_kadane, max_profit_accumulate]\n",
    "\n",
    "CASES = [\n",
    "    ([10, 1, 5, 6, 7, 1], 6),        # example 1\n",
    "    ([10, 8, 7, 5, 2], 0),           # example 2, strictly decreasing\n",
    "    ([7, 1, 5, 3, 6, 4], 5),         # LeetCode's example\n",
    "    ([5], 0),                        # one day, no transaction possible\n",
    "    ([1, 2], 1),                     # two days, profit\n",
    "    ([2, 1], 0),                     # two days, min after max\n",
    "    ([4, 4, 4, 4], 0),               # all equal\n",
    "    ([1, 2, 3, 4, 5], 4),            # increasing: buy first, sell last\n",
    "    ([3, 8, 1, 9], 8),               # a later new low gives the bigger profit\n",
    "    ([2, 9, 1, 4], 7),               # the earlier low still wins\n",
    "    ([0, 100], 100),                 # bounds: price 0 and 100\n",
    "    ([100] * 50 + [0] * 50, 0),      # max length, crash with no recovery\n",
    "]\n",
    "\n",
    "\n",
    "@pytest.mark.parametrize(\"fn\", FNS)\n",
    "@pytest.mark.parametrize(\"prices, expected\", CASES)\n",
    "def test_max_profit(fn, prices, expected):\n",
    "    assert fn(prices) == expected\n",
    "\n",
    "\n",
    "@pytest.mark.parametrize(\"seed\", range(200))\n",
    "def test_random(seed):\n",
    "    rng = random.Random(seed)\n",
    "    prices = [rng.randint(0, 100) for _ in range(rng.randint(1, 100))]\n",
    "    expected = max_profit_brute(prices)\n",
    "    for fn in FNS:\n",
    "        assert fn(prices) == expected"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "d67477be2d71",
   "metadata": {},
   "source": [
    "## 5. Scratch / Experiments\n",
    "\n",
    "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$.\n",
    "\n",
    "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$).\n",
    "\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$."
   ]
  },
  {
   "cell_type": "code",
   "id": "312c61b82d54",
   "metadata": {},
   "source": [
    "rng = random.Random(0)\n",
    "prices = [rng.randint(0, 10_000) for _ in range(100_000)]\n",
    "assert max_profit_mine(prices) == max_profit_sliding_window(prices) == max_profit_kadane(prices) == max_profit_accumulate(prices)\n",
    "%timeit max_profit_mine(prices)\n",
    "%timeit max_profit_sliding_window(prices)\n",
    "%timeit max_profit_kadane(prices)\n",
    "%timeit max_profit_accumulate(prices)\n",
    "\n",
    "small = prices[:2000]\n",
    "assert max_profit_brute(small) == max_profit_mine(small)\n",
    "%timeit -n 1 -r 3 max_profit_brute(small)\n",
    "%timeit max_profit_mine(small)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "0d0c1d33b833",
   "metadata": {},
   "source": [
    "## 6. Takeaways\n",
    "\n",
    "- **Pattern:** **\"best pair `i < j`\" → fix the right end and keep the best left end seen so far.**\n",
    "  Here the best left end is the running minimum, so one pass replaces the $O(n^2)$ pair scan.\n",
    "  Write it as a **sliding window** `[l, r]`: `r` always advances, `l` jumps to `r` when the window\n",
    "  stops being worth keeping (a new low). That shape is the template for every sliding-window problem.\n",
    "  The same trick shows up as \"running max/min + answer at each step\" and as Kadane's algorithm on\n",
    "  the differences.\n",
    "- **Mistakes I made:** none in the algorithm, it's the optimal $O(n)$ / $O(1)$ solution. Polish:\n",
    "  - The `if price - buy > 0` guard is unnecessary: `max_sell` starts at 0, so\n",
    "    `max(max_sell, price - buy)` already ignores non-positive profits. Fewer branches, fewer bugs.\n",
    "  - `return` with no value returns `None`; if you guard empty input, `return 0` to keep the\n",
    "    return type `int`.\n",
    "  - Name things for what they hold: `max_sell` is really the max **profit**, `buy` is the\n",
    "    **min price** so far.\n",
    "- **Related problems:** Best Time to Buy and Sell Stock II (#122, unlimited transactions: sum\n",
    "  every positive daily change), III (#123, at most two transactions) and IV (#188, at most `k`,\n",
    "  DP over states), with Cooldown (#309) and with Transaction Fee (#714) (state-machine DP);\n",
    "  Maximum Subarray (#53, the Kadane view of this problem); Longest Substring Without Repeating\n",
    "  Characters (#3, the next sliding-window problem)."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
