121. Best Time to Buy and Sell Stock

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

Last updated