150强访谈简单

买卖股票的最佳时机

“买卖股票的最佳时机”问题的详细指南和 Python 实施。

问题陈述

简单

给您一个数组 prices,其中 prices[i] 是给定股票在第 i 天的价格。

您希望通过选择某一天购买一只股票并选择未来的另一天出售该股票来最大化您的利润。

返回您可以从本次交易中获得的最大利润。如果您无法获得任何利润,请返回 0

编写一个函数 maxProfit(prices: List[int]) -> int

约束条件
  • 1 <= len(prices) <= 10^5
  • 0 <= prices[i] <= 10^4

示例

Example 1
Input
prices = [7, 1, 5, 3, 6, 4]
Output
5
Explanation

Buy on day 2 (price = 1) and sell on day 5 (price = 6). Profit = 6 - 1 = 5.

Example 2
Input
prices = [7, 6, 4, 3, 1]
Output
0
Explanation

No profitable transaction is possible since prices only decrease.

Need a Hint?
考虑使用滑动窗口特定的数据结构,例如集合或堆。
Edge Cases to Watch
  • 空输入结构
  • 单元素输入
  • 大数值范围

准备好解决了吗?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在编辑器中打开
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推荐的 Python 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。