用 Python 编写程序来找出通过买卖股票可以获得的最大利润?

pythonserver side programmingprogramming更新于 2026/2/16 1:48:17

假设我们有一份按时间顺序排列的公司股票价格列表,我们必须找出通过买卖股票可以获得的最大利润。我们必须先买后卖,并且卖出股票后必须等一天才能再次买入。

因此,如果输入为 prices = [2, 6, 9, 4, 11],则输出将为 11,因为我们可以在 2 买入,然后在 6 卖出,等待一天,然后在 4 买入,然后在 11 卖出。

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

  • s := 0

  • b := -infinity

  • 对于范围从 0 到 prices 大小的 i,执行

    • temp := b

    • b := b 和 (s - prices[i]) 的最大值

    • 如果 i 非零,然后

      • s := s 和 (temp + prices[i - 1]) 的最大值

  • 返回 s 和 (b + prices 的最后一个元素) 的最大值

让我们看看以下实现以便更好地理解:

示例

class Solution:
   def solve(self, prices):
      s = 0
      b = float("-inf")
      for i in range(len(prices)):
         temp = b
         b = max(b, s - prices[i])
         if i:
            s = max(s, temp + prices[i - 1])
      return max(s, b + prices[-1])

ob = Solution()
prices = [2, 6, 9, 4, 11]
print(ob.solve(prices))

输入

[2, 6, 9, 4, 11]

输出

11

相关文章


有用资源