LeetCode热题100-买卖股票的最佳时机

给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。

你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。

返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0 。

这种题目其实一般也假定了数据会有买入和卖出点,只需要找到最低点,在最低点后如果利润大于0就假定会卖出,如果等于0就不会卖出。

python 复制代码
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        min_price = prices[0]
        max_profit = 0

        for price in prices:
            cur_profit = price - min_price

            if cur_profit > max_profit:
                max_profit = cur_profit
            
            if price < min_price:
                min_price = price
        
        return max_profit
相关推荐
Nil2081 天前
leetcode 49字母异位分组
算法·leetcode·哈希算法
Nil2082 天前
leetcode 5最长回文子串
算法·leetcode·职场和发展
m0_674571972 天前
力扣 hot 100 python
python·算法·leetcode
圣保罗的大教堂2 天前
leetcode 3727. 最大交替平方和 中等
leetcode
Xin7702 天前
LeetCode 200. 岛屿数量(DFS 深度优先遍历法)
leetcode
alphaTao2 天前
LeetCode 每日一题 2026/10/12-2026/10/18
算法·leetcode
Cccp.1232 天前
【leetcode】(十三)大数据处理
数据结构·算法·leetcode
Pniubi2 天前
力扣70爬楼梯
数据结构·算法·leetcode
Navigator_Z3 天前
LeetCode //C - 1293. Shortest Path in a Grid with Obstacles Elimination
c语言·算法·leetcode
Nil2083 天前
leetcode 64最小路径和
算法·leetcode·职场和发展