> For the complete documentation index, see [llms.txt](https://algorithm.national-cat.me/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://algorithm.national-cat.me/leetcode/121.-best-time-to-buy-and-sell-stock.md).

# 121. Best Time to Buy and Sell Stock

```php
class Solution {

    /**
     * @param Integer[] $prices
     * @return Integer
     */
    function maxProfit($prices) {
        $cost = $prices[0];
        $maxProfit = 0;
        foreach($prices as $price) {
            // 最小成本
            $cost = min($price, $cost);
            // 最大利潤
            $maxProfit = max($price - $cost, $maxProfit);
        }

        return $maxProfit;
    }
}
```

<https://leetcode.com/problems/best-time-to-buy-and-sell-stock/solutions/3596080/minimum-cost-maximum-profit>
