File: best-time-to-buy-and-sell-stock/solution.py

Date: 2026-06-06

Time: 15:22

best-time-to-buy-and-sell-stock/solution.py

Purpose

This file solves LeetCode #121 — Best Time to Buy and Sell Stock. It finds the maximum profit from a single buy-sell transaction given a time series of stock prices. It's a standalone solution module following the repo's convention of one problem per directory.

Key Components

maxProfit(prices: list[int]) -> int — The sole function. Contract:

Patterns

The solution uses Kadane's-style single-pass tracking — a classic greedy pattern for problems where you need the maximum difference prices[j] - prices[i] with j > i. Instead of checking all O(n²) pairs, it maintains a running minimum and computes the best profit at each step.

This is the same pattern used in maximum-difference-between-increasing-elements/solution.py — track min-so-far, compute max-delta at each position.

Dependencies

Imports: None — pure Python with no library dependencies.

Imported by: The best-time-to-buy-and-sell-stock/test_solution.py file imports this directly. The massive "Imported By" list in the prompt is an artifact of the repo's test infrastructure — those other test files don't actually import this solution; they share a common test harness pattern.

Flow

1. Initialize minprice to the first element and maxprofit to 0.

2. Iterate over prices[1:]. For each price:

3. Return max_profit.

The order of the two updates inside the loop matters: profit is computed *before* min_price is updated, which prevents buying and selling on the same day from inflating the result (though same-day would yield 0 profit anyway, so it's actually safe either way — the ordering is a clarity choice, not a correctness requirement).

Invariants

Error Handling

None. The function trusts its caller to provide a valid, non-empty list of integers. This is consistent with LeetCode's constraints where 1 <= prices.length <= 10^5.