Python中找到至多买卖两次的最大收益的程序
假设我们有一个称为“prices”的数字列表,它按时间顺序表示公司的股票价格,我们必须找出我们最多可以从买卖该股票两次中获得的最大利润。我们必须先购买再出售。
所以,如果输入如“prices = [2, 6, 3, 4, 2, 9]”,则输出将是11,因为我们可以以2的价格买入,然后以6的价格抛出,再以2的价格买入并以9的价格抛出。
要解决此问题,我们将执行以下步骤-
- first_buy:= -inf,first_sell := -inf
- second_buy:= -inf,second_sell := -inf
- 对于价格中的每个px,执行
- first_buy := max(first_buy和-px)
- first_sell := max(first_sell和(first_buy + px))
- second_buy := max(second_buy和(first_sell – px))
- second_sell := max(second_sell和(second_buy + px))
- 返回0、first_sell和second_sell中的最大值
让我们看下面的实现以更好地理解-
更多Python相关文章,请阅读:Python 教程