LC 速查

HOT 100索引 › B14 贪心算法 Greedy

LC 121买卖股票的最佳时机Best Time to Buy and Sell Stock 简单

给定股票每天的价格,只能买入和卖出一次,求能获得的最大利润,不做交易则为 0。

思路 一次遍历维护历史最低价 lo,用当天价减最低价更新答案。时间 O(n)。

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        ans = 0
        lo = inf
        for p in prices:
            ans = max(ans, p - lo)
            lo = min(lo, p)
        return ans
← 上一题 数据流的中位数跳跃游戏 下一题 →