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]
输出
6
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP