本题主要是是求序列中两个数字的最大差,其中第一个数必须在第二个数前面
O(n)就可以解决问题
class Solution:
def maxProfit(self, prices: List[int]) -> int:
max_profit = 0
min_index = 0
for i in range(len(prices)):
if prices[i] - prices[min_index] > max_profit:
max_profit = prices[i] - prices[min_index]
elif prices[i] < prices[min_index]:
min_index = i
return max_profit

本文介绍了一种在O(n)时间复杂度内找到给定价格序列中最佳买卖时机的方法,以实现最大利润。通过维护一个当前最低价格和不断更新最大利润来实现。

被折叠的 条评论
为什么被折叠?



