用 Python 编写程序,找出在股票市场上买入一次可以获得的最大利润

pythonserver side programmingprogramming更新于 2026/1/8 21:00:17

假设我们有一份按时间顺序排列的代表某家公司股票价格的价格列表,我们必须找出只买入和卖出一次该股票可以获得的最大利润。我们必须记住,我们必须先买,然后才能卖。

因此,如果输入为 prices = [10, 12, 9, 6, 8, 12],则输出将为 6,因为我们可以以 6 买入并以 12 卖出。

为了解决这个问题,我们将遵循以下步骤 −

  • max_profit := 0
  • min_stock := infinity
  • 对于 prices 中的每个价格,执行
    • max_profit := max_profit 和 (price - min_stock) 的最大值
    • min_stock := min_stock 和 price 的最小值
  • 返回 max_profit

让我们看看下面的实现以便更好地理解 −

示例

class Solution:
   def solve(self, prices):
      max_profit = 0
      min_stock = float('inf')
      for price in prices:
         max_profit = max(max_profit, price - min_stock)
         min_stock = min(min_stock, price)
      return max_profit
ob = Solution()
print(ob.solve([10, 12, 9, 6, 8, 12]))

输入

[10, 12, 9, 6, 8, 12]

输出

6

相关文章


有用资源