Python程序:求解买卖股票最大利润
假设我们按时间顺序获得了一个公司股票价格的列表,我们需要找到通过买卖股票可以获得的最大利润。必须先买入后卖出,并且卖出股票后必须等待一天才能再次买入。
因此,如果输入类似 prices = [2, 6, 9, 4, 11],则输出为 11,因为我们可以以 2 买入,以 6 卖出,等待一天,然后以 4 买入,然后以 11 卖出。
为了解决这个问题,我们将遵循以下步骤:
s := 0
b := -∞
对于 i 从 0 到 prices 的大小,执行:
temp := b
b := max(b, (s - prices[i]))
如果 i 非零,则:
s := max(s, (temp + prices[i - 1]))
返回 max(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
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP