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
相关推荐
穿条秋裤到处跑5 小时前
每日一道leetcode(2026.04.29):二维网格图中探测环
算法·leetcode·职场和发展
水蓝烟雨11 小时前
1931. 用三种不同颜色为网格涂色
算法·leetcode
leoufung12 小时前
LeetCode 76:Minimum Window Substring 题解与滑动窗口思维详解
算法·leetcode·职场和发展
风筝在晴天搁浅14 小时前
LeetCode 92.反转链表Ⅱ
算法·leetcode·链表
普贤莲花17 小时前
【2026年第18周---写于20260501】---舍得
程序人生·算法·leetcode
m0_6294947318 小时前
LeetCode 热题 100-----16.除了自身以外数组的乘积
数据结构·算法·leetcode
We་ct18 小时前
LeetCode 97. 交错字符串:动态规划详解
前端·算法·leetcode·typescript·动态规划
无敌昊哥战神19 小时前
【LeetCode 37】解数独 (Sudoku Solver) —— 回溯法详解 (Python/C/C++)
c语言·c++·python·算法·leetcode
风筝在晴天搁浅19 小时前
LeetCode 162.寻找峰值
算法·leetcode
罗超驿20 小时前
双指针算法经典案例:LeetCode 283. 移动零(Java详解)
java·算法·leetcode