Python程序:求解股票市场单次交易最大利润


假设我们有一份价格列表,按时间顺序表示某公司股票的价格,我们需要找到仅进行一次买卖所能获得的最大利润。请记住,必须先买入才能卖出。

因此,如果输入类似于 prices = [10, 12, 9, 6, 8, 12],则输出为 6,因为我们可以在价格为 6 时买入,在价格为 12 时卖出。

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

  • max_profit := 0
  • min_stock := 无穷大
  • 对于 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]

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

输出

6

更新于:2020年10月5日

1K+ 浏览量

开启您的职业生涯

完成课程获得认证

开始学习
广告