内卷地狱

121. Best Time to Buy and Sell Stock

Edit Me

Problem

121. Best Time to Buy and Sell Stock

Approach

Dynamic programming — find the minimum problem.

Recurrence: the maximum profit on day i = max(maximum profit on day i-1, price on day i − minimum price before day i)

Code

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        # Recurrence: max profit on day i = max(max profit on day i-1, price on day i - min price before day i-1)
        dp = [0] * len(prices)
        min_price = prices[0]
        for i in range(1, len(prices)):
            dp[i] = max(dp[i - 1], prices[i] - min_price)
            min_price = min(min_price, prices[i])
        return dp[-1]

贡献者


这篇文章有帮助吗?

最近更新

Involution Hell© 2026 byCommunityunderCC BY-NC-SA 4.0CCBYNCSA