Python程序:求解股票市场多次交易的最大利润
假设我们有一列价格,代表公司股票按时间顺序排列的价格,我们需要找到通过多次买卖股票可以获得的最大利润。记住,必须先买入才能卖出。
因此,如果输入类似 prices = [10, 50, 30, 40, 60],则输出为 70,因为我们可以以 10 买入,以 50 卖出,以 30 买入,以 60 卖出。
为了解决这个问题,我们将遵循以下步骤:
- prev_price := 无穷大
- profit := 0
- 对于 prices 中的每个 p,执行:
- 如果 p > prev_price,则
- profit := profit + p - prev_price
- prev_price := p
- 如果 p > prev_price,则
- 返回 profit
让我们看下面的实现,以便更好地理解:
示例
class Solution:
def solve(self, prices):
prev_price = float("inf")
profit = 0
for p in prices:
if p > prev_price:
profit += p - prev_price
prev_price = p
return profit
ob = Solution()
print(ob.solve([10, 50, 30, 40, 60]))输入
[10, 50, 30, 40, 60]
输出
70
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP