题目

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

给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。
你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。
返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0 。

自解

暴力解法——题解说超时了

1
2
3
4
5
6
7
8
def maxProfit(self, prices: List[int]) -> int:
maxprofit = 0
minprice = 1e9
for i in range(len(prices)):
for j in range(i+1,len(prices)):
maxprofit=max(prices[j]-prices[i],maxprofit)
return maxprofit

题解

一次遍历

1
2
3
4
5
6
7
def maxProfit(self, prices: List[int]) -> int:
maxprofit = 0
minprice = float('inf')
for i in range(len(prices)):
maxprofit = max(prices[i] - minprice, maxprofit)
minprice = min(prices[i], minprice)
return maxprofit

比较有启发的应该是可以在 max() 里再次比较最大值

对于有顺序要求的情况,枚举右,查找左一般比较容易。

关于更新最大利润和最小价格顺序的问题还没有搞清楚


https://yohakuo.github.io/2025/12/25/买卖股票的最佳时机/
作者
新喀鸦006
发布于
2025年12月25日
许可协议