🎃

100日アルゴリズム[6日目・動的計画法]

2024/03/27に公開

解いた問題

https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/

回答

function maxProfit(prices: number[]): number {
    let minPrice = prices[0];
    let maxProfit = 0; 

    for (let i = 1; i < prices.length; i++) {
        const currentPrice = prices[i];
        minPrice = Math.min(minPrice, currentPrice);
        maxProfit = Math.max(maxProfit, currentPrice - minPrice);
    }

    return maxProfit;
};

Discussion